相关疑难解决方法(0)

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

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

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)

php arrays casting object

18
推荐指数
1
解决办法
2234
查看次数

标签 统计

arrays ×1

casting ×1

object ×1

php ×1