ShaShads
ShaShads

Reputation: 572

PHP 5.4 new object -> call method

I thought in php 5.4 this was possible

(new object())->method();

But I am having trouble when both the object and methods are stored in a classes variables I have tried the following,

new $this->object($this->params)->$this->method();
new ($this->object($this->params))->$this->method();
new $this->object($this->params)->{$this->method}();

I can't seem to get it working unless I am mistaken and it cannot be done. Thank you

Upvotes: 1

Views: 1937

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270795

Based on this test (http://codepad.viper-7.com/mcPvpG) (updated test), it ought to work if you wrap the new object() in its own (), and wrap the method name in {}. Because it is the expression new object() which returns the object, rather than just the call to the constructor object(), that expression needs to be wrapped as ().

This is super-convoluted though. If you have the opportunity to rethink this, I would do so.

public $object = 'ClassName';
public $method = 'method';

// Called as:
(new $this->object($this->params))->{$this->method}();

Here's an example using ArrayIterator::valid():

class instantiator {
    public $object = "ArrayIterator";
    public $method = "valid";
    public $params = array(1,2,3);

    public function do_it() {
        var_dump((new $this->object($this->params))->{$this->method}());
    }
}

$i = new instantiator();
$i->do_it();
// Prints bool(true)

Upvotes: 3

Related Questions