整数属性
这指的是名称是十进制整数的字符串表示形式的属性。例如:
$o = new stdClass;
$o->{"123"} = 'foo'; // create a new integer property
echo $o->{"123"}, PHP_EOL; // verify it's there
$a = (array)$o; // convert to array
echo $a['123']; // OOPS! E_NOTICE: Undefined offset!
var_dump(array_keys($a)); // even though the key appears to be there!
print_r($a); // the value appears to be there too!
一般来说,如果你重视你的理智,PHP 中的整数属性不是你应该接近的东西。
前置值由null
对于private
和protected
属性,生成的数组键将包含不可打印字符"\0"
。这可能很有用(因为该字符对于属性名称是不合法的,您可以使用此信息来确定属性的可见性),但如果您不希望它存在,它也可能是一个麻烦。例子:
class A {
private $A; // This will become '\0A\0A'
}
class B extends A {
private $A; // This will become '\0B\0A'
public $AA; // This will become 'AA'
}
$a = (array) new B();
// The array appears to have the keys "BA", "AA" and "AA" (twice!)
print_r(array_keys($a));
// But in reality, the 1st and 3rd keys contain NULL bytes:
print_r(array_map('bin2hex', array_keys($a)));
您可以从数组键中提取可见性信息,如下所示:
$a = (array) new B();
foreach ($a as $k => $v) {
$parts = explode(chr(0), $k);
if (count($parts) == 1) {
echo 'public $'.$parts[0].PHP_EOL;
}
else if ($parts[1] == "*") {
echo 'protected $'.$parts[2].PHP_EOL;
}
else {
echo 'private '.$parts[1].'::$'.$parts[2].PHP_EOL;
}
}