动态属性不是PHP专有的,很多解释型语言都有这个功能,比如javascript。它可以动态的为其对象添加删除属性。PHP也可以动态的添加属性,如下面的例子:
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>'
;
|
这让人想起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 objectwith properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.
1
2
3
4
|
<?php
$obj
= (object)
'ciao'
;
echo
$obj
->scalar;
// outputs 'ciao'
?>
|
简单的说,就是一个某种类型的值转换成对象时候,就会创建一个stdClass的实例。再看文档中提供例子,一个标量类型的值,转换成object。
进一步,如果运行如下代码:
1
|
echo
'$obj instanceof stdClass='
,(
$obj
instanceof
stdClass)?
'Y'
:
'N'
,
'<br>'
;
|
我们得到的结果是:
$obj instanceof stdClass=Y
也就是说转变成对象的时候,是创建了一个stdClass,然后再动态添加属性并且赋值。用var_dump方法也可以看出类型是stdClass。
理论上,我们可以手动的实例化一个stdClass,并通过var_dump查看他。
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保留的,没有属性也没有任何方法的一个空对象,其作用就是为了在对象转换时候,生成它,并且动态的添加属性来完成对象的赋值。
参考文档:
http://krisjordan.com/dynamic-properties-in-php-with-stdclass
http://php.net/manual/en/language.types.object.php
本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/1301423 ,如需转载请自行联系原作者