作者:细野本尊 | 来源:互联网 | 2023-09-13 14:41
Canyouexplainthenextinterestingbehaviour?你能解释下一个有趣的行为吗?classtest{Class*test*hastw
Can you explain the next interesting behaviour?
你能解释下一个有趣的行为吗?
class test {
//Class *test* has two properties, public and private.
public $xpublic = 'x1';
private $xprivate = 'x2';
}
$testObj = new test();
Let's convert $testObj
to array.
让我们将$ testObj转换为数组。
settype($testObj, 'array');
var_dump($testObj);
Result:
结果:
array(2) {
["xpublic"]=> string(3) "x1"
["testxprivate"]=> string(4) "x2"
}
OK, xprivate
property becomes testxprivate
好的,xprivate属性变为testxprivate
Let's convert this array to object.
让我们将这个数组转换为object。
$newObj = (object)$testObj;
var_dump($newObj);
Result:
结果:
object(stdClass)#1 (2) {
["xpublic"]=> string(3) "xxx"
["xprivate":"test":private]=> string(4) "xxx3"
}
$newObj
is a stdClass
object.
$ newObj是一个stdClass对象。
And the question is:
问题是:
Why does testxprivate
become a private property xprivate
(not testxprivate
) of the new object? How does PHP know that $testObj
array was an object?
为什么testxprivate成为新对象的私有属性xprivate(而不是testxprivate)? PHP如何知道$ testObj数组是一个对象?
If I define the equal array:
如果我定义相等的数组:
$testArray = array('xpublic'=>'x1', 'testxprivate'=>'x2');
and then convert it to object:
然后将其转换为对象:
var_dump((object)$testArray);
I'll get the object with two public properties xpublic
and testxprivate
as expected:
我将按预期获得具有两个公共属性xpublic和testxprivate的对象:
object(stdClass)#2 (2) {
["xpublic"]=> string(2) "x1"
["testxprivate"]=> string(2) "x2"
}
2 个解决方案