【发布时间】:2011-09-13 14:29:48
【问题描述】:
你能解释下一个有趣的行为吗?
class test {
//Class *test* has two properties, public and private.
public $xpublic = 'x1';
private $xprivate = 'x2';
}
$testObj = new test();
让我们将$testObj 转换为数组。
settype($testObj, 'array');
var_dump($testObj);
结果:
数组(2){
["xpublic"]=> 字符串(3) "x1"
["testxprivate"]=> 字符串(4) "x2"
}
好的,xprivate 属性变为testxprivate
让我们将此数组转换为对象。
$newObj = (object)$testObj;
var_dump($newObj);
结果:
object(stdClass)#1 (2) {
["xpublic"]=> 字符串(3) "xxx"
["xprivate":"test":private]=> 字符串(4) "xxx3"
}
$newObj 是一个stdClass 对象。
问题是:
为什么testxprivate 成为新对象的私有属性xprivate(而不是testxprivate)? PHP如何知道$testObj数组是一个对象?
如果我定义相等数组:
$testArray = array('xpublic'=>'x1', 'testxprivate'=>'x2');
然后将其转换为对象:
var_dump((object)$testArray);
我将按预期获得具有两个 public 属性 xpublic 和 testxprivate 的对象:
object(stdClass)#2 (2) {
["xpublic"]=> 字符串(2) "x1"
["testxprivate"]=> 字符串(2) "x2"
}
【问题讨论】: