標籤:
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的東西將屬性給動態添加進去,我好像查到過什麼魔幻函數
PHP學習筆記