How to call function of just created object without temporary variable?
Code
(new \Foo())->woof();
is not valid in php.
What is right?
How to call function of just created object without temporary variable?
Code
(new \Foo())->woof();
is not valid in php.
What is right?
It can work if the object has singleton
Foo::getInstance()->woof();
BTW: it doesn't have to be even singleton but also static method which returns the instance
class Foo {
public static function & getInstance()
{
return new self();
}
}
$obj = new Foo();
$obj->woof();
Sorry, no chaining allowed here.
You need some form of a temporary variable. This work, but it's kinda hackish:
(${''} = new Foo())&&${''}->woof();
I like this solution because ${''} is the only way you can access this variable, so it's ok for temporary ones.
You can do it like this, but it's not very clean:
<?php
class Foo
{
public function __construct()
{
}
public function bar()
{
echo 'hello!';
}
}
function Foo()
{
return new Foo();
}
Foo()->bar();
You could also change it to something like
function newClass($className)
{
return new $className();
}
newClass('Foo')->bar();
But the static method way is preferred.