PHP Object stuff
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.
I do this with some of my stuff:
class Test
{
protected function __construct() {
// some config stuff...set some stuff
}
static function getInstance() {
return new Test();
}
public function printMsg($msg) {
print $msg;
return $this;
}
public function arg() {
print 'I AM AN ANGRY METHOD!';
return $this;
}
}
Test::getInstance()->printMsg('this is a test')->arg();
Of course I do more interesting stuff with it than prints…model stuff and what have you.
-
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();
-
spiteshow reblogged this from marco and added:
some of my stuff:...Test { protected...__construct() { //...
-
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
-
derekreynolds reblogged this from marco and added:
instance of itself in the constructor? // constructor...$this; Then when creating
-
marco posted this