如果有人能解释我下面的行为,我将不胜感激(同时;)更明智(:
我们有一个班级。
class Test {
public $id;
private $name;
protected $color;
}
我们有我不完全理解的ReflectionProperty构造函数行为。
先工作一个:
function check() {
$class = new Test();
$ref = new ReflectionObject($class);
$pros = $ref->getProperties();
foreach ($pros as $pro) {
false && $pro = new ReflectionProperty();
print_r($pro);
}
}
这将给出以下正确输出:
ReflectionProperty Object
(
[name] => id
[class] => Test
)
ReflectionProperty Object
(
[name] => name
[class] => Test
)
ReflectionProperty Object
(
[name] => color
[class] => Test
)
现在:如果我从这一行中删除"false":
false && $pro = new ReflectionProperty();
输出将是:
PHP Fatal error: Uncaught ArgumentCountError: ReflectionProperty::__construct() expects exactly 2 parameters, 0 given
ReflectionProperty::__construct(( takes ($class, $name(
因此,问题是:为什么"假"甚至首先有效?
这与 ReflectionProperty 构造函数本身无关。
false && $pro = new ReflectionProperty();
是所谓的短路。这意味着右侧的代码只会在需要时执行。在这种情况下,因为你正在执行一个&&&(AND(,左侧为假,引擎知道结果永远不会等于真,所以它不需要执行和评估右侧,即你的ReflectionProperty构造函数。
基本上,false && 正在阻止您损坏的代码运行,然后print_r 使用 getProperties 结果中的现有 pro 值。
false && $pro = new ReflectionProperty();
的计算结果为false
。
因为第一个条件是false
,所以不需要评估第二个$pro = new ReflectionProperty()
(称为"短路评估"(。
当您删除false
时,您有线条
$pro = new ReflectionProperty();
并且ReflectionProperty
构造函数需要两个参数(错误消息告诉您这一点(。