PHP,你怎么穿着品如的衣服? 作者: LiesAuer 时间: 2019-04-19 分类: 开发 ## 运行环境 1. `PHP >= 5.4` 然而如果你的 `PHP` 版本小于 `7.1`,这段代码还是跑不了,会报`PHP Fatal error: Cannot access empty property`,要将以下语句移除才能运行起来 ```text null => '我是null', $prop = null; var_dump($dynamicVar->$prop); ``` 我猜测应该是 `PHP 7.1` 加强了对 `nullable` `void` 的支持,所以导致了属性可以为 `null` 的诡异写法。 ```php $value) { $this->$var = $value; } } } $dynamicVar = new DynamicObj([ null => '我是null', 0 => '我是数字', '1' => '我也是数字', '0我是_- 非法属性名☺' => '。。。', 0x123456 => 'hex test', ]); var_dump($dynamicVar); $prop = null; var_dump($dynamicVar->$prop); var_dump($dynamicVar->{'0我是_- 非法属性名☺'}); var_dump($dynamicVar->{0x123456}); $json = json_encode($dynamicVar); var_dump($json); var_dump(json_decode($json)); var_dump(json_decode($json, true)); ``` ```text /Users/imac/Desktop/test.php:21: class DynamicObj#1 (5) { public $ => string(10) "我是null" public $0 => string(12) "我是数字" public $1 => string(15) "我也是数字" public $0我是_- 非法属性名☺ => string(9) "。。。" public $1193046 => string(8) "hex test" } /Users/imac/Desktop/test.php:25: string(10) "我是null" /Users/imac/Desktop/test.php:27: string(9) "。。。" /Users/imac/Desktop/test.php:29: string(8) "hex test" /Users/imac/Desktop/test.php:33: string(188) "{"":"\u6211\u662fnull","0":"\u6211\u662f\u6570\u5b57","1":"\u6211\u4e5f\u662f\u6570\u5b57","0\u6211\u662f_- \u975e\u6cd5\u5c5e\u6027\u540d\u263a":"\u3002\u3002\u3002","1193046":"hex test"}" /Users/imac/Desktop/test.php:35: class stdClass#2 (5) { public $ => string(10) "我是null" public $0 => string(12) "我是数字" public $1 => string(15) "我也是数字" public $0我是_- 非法属性名☺ => string(9) "。。。" public $1193046 => string(8) "hex test" } /Users/imac/Desktop/test.php:36: array(5) { '' => string(10) "我是null" [0] => string(12) "我是数字" [1] => string(15) "我也是数字" '0我是_- 非法属性名☺' => string(9) "。。。" [1193046] => string(8) "hex test" } ``` 突然觉得这么多年PHP白学了 标签: none