PHP学习笔记-动态属性添加

PHP中类动态属性的添加

从stdClass说起,查找这个类得到如下的定义

stdClass在PHP5才开始被流行。而stdClass也是zend的一个保留类。stdClass类是PHP的一个内部保留类,初始时没有成员变量也没成员方法,所有的魔术方法都被设置为NULL.凡是用new stdClass()的变量,都不可能会出现$a->test()这种方式的使用。PHP5的对象的独特性,对象在任何地方被调用,都是引用地址型的,所以相对消耗的资源会少一点。在其它页面为它赋值时是直接修改,而不是引用一个拷贝。

但是我却看到下面的代码:

$CFG = new stdClass();

$CFG->dbtype = 'mysqli';
$CFG->dblibrary = 'native';
$CFG->dbhost = 'localhost';
$CFG->dbname = 'moodle26';
$CFG->dbuser = 'raoqiang';
$CFG->dbpass = 'wodemima';
$CFG->prefix = 'mdl_';
$CFG->dboptions = array (
'dbpersist' => 0,
'dbsocket' => 0,
);

查了以下知道了,有同样的问题就是这样

<?php
class Foo{
        
}
$foo = new Foo();
var_dump($foo);
$foo->test = 'aaaaaaaa'; 
var_dump($foo);
$foo->show = 'bbbbbbbbbbbb';
var_dump($foo);


///////////////////////////////////////////////

就是这样的东西,本身的类并没有定义变量但是却可以再实例化的时候动态的给它添加进去,感觉很诡异啊

不能理解为何这个没有任何成员变量和成员方法的类可以给随意的赋值给成员变量,并且好像这些成员变量一开始并没有定义过的,然后我就查一查,各种查

最后查到这是一种动态添加属性的方法

再PHp的手册中也叫Overload方法

http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

Overloading ¶

Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.

All overloading methods must be defined as public.

Note:

None of the arguments of these magic methods can be passed by reference.

Note:

PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

Changelog ¶

这上面的讨论可以把问题描述清楚,但是好像并没解释清楚,于是有人给了上面的手册中的OVERLOAD的解释

这个解释就是说这个类可以通过一个叫magic methods的东西将属性给动态添加进去,我好像查到过什么魔幻函数

原文地址:https://www.cnblogs.com/Erdos001/p/4583657.html