Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining a new object instance in PHP

Tags:

php

We have the following chaining:

$obj = new obj();
$obj->setname($params1)->setcolor($params2);

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

$obj = new obj()->setname($params1)->setcolor($params2);
like image 363
Дамян Станчев Avatar asked Mar 23 '26 08:03

Дамян Станчев


1 Answers

Since PHP 5.4, class member access on instantiation has been added so you can do it like this:

$obj = (new obj())->setname($params1)->setcolor($params2);

In previous versions, like you I hate that you have to instantiate the object on one line and then start using it on another, so I have a global function _i() which looks like this:

function _i($i) { return $i; }

I use it like this:

_i(new Obj)->doThis($param)->doThat($param2);

Some people will find it ugly but PHP lacks language expression power, so it works for me :)

like image 136
ddinchev Avatar answered Mar 24 '26 22:03

ddinchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!