delavey
delavey

Reputation: 93

ReflectionProperty constructor

I'll be grateful (and wiser at the same time ;) ) if anyone can explain me below behavior:

We've got a class.

class Test {
    public $id;
    private $name;
    protected $color;
}

And we've got ReflectionProperty constructor behavior that I do not fully understand.

Working one first:

function check() {
    $class = new Test();
    $ref = new ReflectionObject($class);
    $pros = $ref->getProperties();
    foreach ($pros as $pro) {
        false && $pro = new ReflectionProperty();
        print_r($pro);
    }
}

This will give correct output of:

ReflectionProperty Object
(
    [name] => id
    [class] => Test
)
ReflectionProperty Object
(
    [name] => name
    [class] => Test
)
ReflectionProperty Object
(
    [name] => color
    [class] => Test
)

Now: if I remove "false" from this line:

false && $pro = new ReflectionProperty();

the output will be:

PHP Fatal error:  Uncaught ArgumentCountError: ReflectionProperty::__construct() expects exactly 2 parameters, 0 given

ReflectionProperty::__construct() takes ($class, $name)

The question therefore is: why 'false' even works in the first place?

Upvotes: 1

Views: 126

Answers (2)

Mark R
Mark R

Reputation: 136

It's nothing to do with the ReflectionProperty constructor itself.

false && $pro = new ReflectionProperty();

Is something called a short circuit. It means that the code on the right will only execute if it needs to. In this case, because you're doing a && (AND) with the left side being false, the engine knows that the result can NEVER equal true, and so it doesn't need to execute and evaluate the right hand side, which is your ReflectionProperty constructor.

Basically, the false && is stopping your broken code from running, and print_r is then using the existing value of pro from the getProperties results.

Upvotes: 4

u_mulder
u_mulder

Reputation: 54841

false && $pro = new ReflectionProperty(); evaluates to false.

Because first condition is false, there's no need to evaluate second $pro = new ReflectionProperty() (it's called "short circuit evaluation").

When you remove false you have line

$pro = new ReflectionProperty();

and ReflectionProperty constructor requires two arguments (and error message tells you about this).

Upvotes: 2

Related Questions