PHP中的数组到Object和Object to Array - 有趣的行为

And*_*ndy 18 php arrays casting object

你能解释下一个有趣的行为吗?

class test {
  //Class *test* has two properties, public and private.
  public $xpublic = 'x1';
  private $xprivate = 'x2';
}
$testObj = new test();
Run Code Online (Sandbox Code Playgroud)

让我们转换$testObj为数组.

settype($testObj, 'array');
var_dump($testObj);
Run Code Online (Sandbox Code Playgroud)

结果:

array(2) {
  ["xpublic"]=> string(3) "x1"
  ["testxprivate"]=> string(4) "x2"
}

好的,xprivate财产变成了testxprivate

让我们将这个数组转换为object.

$newObj = (object)$testObj;
var_dump($newObj);
Run Code Online (Sandbox Code Playgroud)

结果:

object(stdClass)#1 (2) {
  ["xpublic"]=> string(3) "xxx"
  ["xprivate":"test":private]=> string(4) "xxx3"
}

$newObj是一个stdClass对象.

问题是:

为什么testxprivate成为新对象的私有财产xprivate(而不是testxprivate)?PHP如何知道该$testObj数组是一个对象?

如果我定义相等的数组:

$testArray = array('xpublic'=>'x1', 'testxprivate'=>'x2');
Run Code Online (Sandbox Code Playgroud)

然后将其转换为对象:

var_dump((object)$testArray);
Run Code Online (Sandbox Code Playgroud)

我有两个获得对象的公共属性xpublictestxprivate预期:

object(stdClass)#2 (2) {
  ["xpublic"]=> string(2) "x1"
  ["testxprivate"]=> string(2) "x2"
}

hak*_*kre 20

数组键包含一个标记,该标记应该是类测试的私有属性.

将脚本输出与以下内容进行比较:

$array = array(
    "xpublic" => "x1", 
    # this will become a private member:
    "\x00test\x00xprivate" => "x2",
    # this will become a protected member:
    "\x00*\x00xprotected" => "x3"
);

var_dump($array);

$obj = (object) $array;

var_dump($obj);
Run Code Online (Sandbox Code Playgroud)

序列化时,使用相同的字符串来描述私有成员.

输出:

array(3) {
  ["xpublic"]=>
  string(2) "x1"
  ["testxprivate"]=>
  string(2) "x2"
  ["*xprotected"]=>
  string(2) "x3"
}

object(stdClass)#1 (3) {
  ["xpublic"]=>
  string(2) "x1"
  ["xprivate":"test":private]=>
  string(2) "x2"
  ["xprotected":protected]=>
  string(2) "x3"
}

在输出中var_dump(),空字节不可见.

(更新:添加受保护的类成员)