Object and Array dereferencing
There’s been quite alot of talk lately about array dereferencing which I think will be included in php 5.4.
Here I’ll show you a couple of tricks I use for array and object dereferencing.
More details on function array dereferencing wiki.php.net
We can already chain methods by returning objects from methods.
Example
class Foo {
public function storeMessage($message) {
$this->message = $message;
return $this;
}
public function showMessage() {
reutrn $this->message;
}
}
$foo = new Foo();
echo $foo->storeMessage('hello world')->showMessage();
Chaining is great (but don’t get too carried away). Sometimes we don’t even need to keep the new object we create because we can do everything we want to do with it in a short space of code. Here it becomes handy to be able to redreference the object at construct.
echo (new Foo())->storeMessage('hello world')->showMessage();
Theres nothing wrong with that apart from you need php 5.4 to do it.
Using the with function work around.
function with($object) {
return $object;
}
echo with(new Foo())->storeMessage('hello world')->showMessage();
Very short function which just returns the object it was given.
Array dereferencing is being able to access an element in the array when it’s returned from a method or function.
Example
function giveMeAnArray() {
return array('color' => 'red', 'size' => 12);
}
echo giveMeAnArray()['color'];
This would produce an error until php 5.4.
The work around I use. Example
function giveMeAnArray() {
return array('color' => 'red', 'size' => 12);
}
echo array_get(giveMeAnArray(), 'color');
Now array_get doesn’t exist in php core. But is a function I find quite handy.