动态属性不是PHP专有的,很多解释型语言都有这个功能,比如javascript。它可以动态的为其对象添加删除属性。PHP也可以动态的添加属性,如下面的例子:
class testClass
{
public $A='a';
}
$t=new testClass();
echo $t->A,'';
echo 'B isset=',isset($t->B)?'Y':'N','';//$t中并没有变量B
$t->B='b';//$t中给添加了变量B,并且赋值。
echo 'B isset=',isset($t->B)?'Y':'N','';
echo '$t->B=',$t->B,'';
unset($t->B);//$t中给删除变量B。
echo 'B isset=',isset($t->B)?'Y':'N',''; 这让人想起PHP中的魔术方法,__get和__set,这两个魔术方法也可以完成这种类似的功能,但是使用他们就显得复杂。因此只有当一些比较复杂的情况下才会使用 这魔术方法。
有了这种动态属性添加的能力,你可以定义一个空的类,然后随时随地,在要用到属性的时候自动添加,很方便。
这种动态属性添加的能力,在类型转换的时候显得很有用。在类型转换的时候,不得不提到stdClass,它是PHP中一个保留的类。官方文档对于这个stdClass描述甚少。下面官方文档的描述: Converting to object
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.