I understand how chaining methods works, I also understand how chaining a property as the last item in the chain works, like this example
$tank = $bmw -> fill(10) -> ride(40) -> tank;
but what about chaining a property in between two methods, how does that work? is the property secretly a method? here is an example
expect(2,2)->not->toBeGreaterThan(3)
I am learning php in the context of laravel so if this is a laravel only thing let me know.
I’ve done my due diligence and looked this up several times but I couldn’t find the answer I am looking for.
>Solution :
expect(2,2) might return an instance of Expectation class. The not is actually a method __get in PHP that returns an instance of the same or other class with some state marked as "negative assertion". toBeGreaterThan(3) is a method that uses to perform the assertion.
it’s the Expectation class:
(new Expectation(2))->not->toBeGreaterThan(3);
class Expectation {
protected $negate = false;
protected $value;
public function __construct($value) {
$this->value = $value;
}
public function __get($name) {
if ($name === 'not') {
$this->negate = true;
return $this;
}
}
public function toBeGreaterThan($limit) {
if ($this->negate) {
assert($this->value <= $limit, "Expected value not to be greater than $limit");
} else {
assert($this->value > $limit, "Expected value to be greater than $limit");
}
}
}
when you access $this->not, PHP will call the magic __get method with ‘not’ as its argument. Inside that method, you can decide what you want to return. In this case, it flips a "negate" flag and returns the same object.
Moreover, this is not a Laravel only thing. It’s a more general PHP pattern.