Can PHP do this?
(new Whatever())->function();It gives me a parse error and makes me do this instead:
$w = new Whatever(); $w->function();But you can do this perfectly well:
$w->function()->otherFunction();One hack is to define a function with the same name as the class that returns an instance:
function Whatever() { return new Whatever(); } /* ... */ Whatever()->function()->otherFunction();But that’s a hack.
Can’t you just return an instance of itself in the constructor?
// constructor
return $this;
Then when creating a new object
$obj = new Class()->method();
Source: marco
11 Notes/ Hide
-
lebird liked this
-
shabdar liked this
-
jaytee reblogged this from marco and added:
should be static if you’re wanting to call it this way. :function();
-
derekreynolds reblogged this from answers and added:
What a bust. It made sense. Thanks for the correction!
-
answers reblogged this from derekreynolds and added:
No, that’s the same parse error. (new Class())->func() and new Class()->func are parsed identically.
-
9-bits liked this
-
marco posted this