2024.12.10
The weird evolution of PHP
PHP is kinda weird-ish language of weird-ish evolution.
$a = new class { public readonly object $b; public readonly object $c; public function __construct() { $this->b = new class { public function helloworld() { return 'hello world'; } }; } };
Let's assume you found yourself with 2 properties in an object and only one of them was initialized (thrift times).
Everything is clear with the lucky initialized:
echo $a->b?->helloworld(); // hello world
But if you will do the same with non-initialized property then everything will abrupt:
echo $a->c?->helloworld(); // Typed property class@anonymous::$c must not be accessed before initialization
Not the best expectations fulfillment when there is nothing after so you are forced to check an extra check:
if (isset($a->c)) { echo echo $a->c->helloworld(); }
And what when we want to check something inside this propery right in check?
if (isset($a->c) && $a->c->isValid()) { return true; }
No reasonable explanation can explain why ?->
dies if propery wasn't initialized and you have to add isset()
, but ??
just doesn't care about property initialization and it's an actual replace for isset()
. So..
echo ($a->c ?? null)?->helloworld(); if (($a->c ?? null)?->isValid()) { return true; }
Very noice, very butiful!