【PHP动态属性和stdclass】
1
2
3
4
5
6
7
8
9
10
11
12
|
class testClass { public $A = 'a' ; } $t = new testClass(); echo $t ->A, '<br>' ; echo 'B isset=' ,isset( $t ->B)? 'Y' : 'N' , '<br>' ; //$t中并没有变量B $t ->B= 'b' ; //$t中给添加了变量B,并且赋值。 echo 'B isset=' ,isset( $t ->B)? 'Y' : 'N' , '<br>' ; echo '$t->B=' , $t ->B, '<br>' ; unset( $t ->B); //$t中给删除变量B。 echo 'B isset=' ,isset( $t ->B)? 'Y' : 'N' , '<br>' ; |
Converting to object
1
2
3
4
|
<?php $obj = (object) 'ciao' ; echo $obj ->scalar; // outputs 'ciao' ?> |
1
|
echo '$obj instanceof stdClass=' ,( $obj instanceof stdClass)? 'Y' : 'N' , '<br>' ; |
1
2
3
4
|
<?php $s = new stdClass(); var_dump( $s ); ?> |
object(stdClass)[1]
也就是说stdClass既没有属性也没有任何方法,是一个空的对象。
有不少人认为stdClass类似C#中的object,认为PHP中所有的类都继承于stdClass,这是错误的,下面的代码就能说明问题了。
1
2
3
|
class Foo{} $foo = new Foo(); echo ($foo instanceof stdClass)? 'Y' : 'N' ; |
因此可以总结如下:
stdClass是PHP保留的,没有属性也没有任何方法的一个空对象,其作用就是为了在对象转换时候,生成它,并且动态的添加属性来完成对象的赋值。