1

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

3
  • 4
    That is some terrible code right there that is Commented Mar 3, 2013 at 19:07
  • I understand it is hard to understand but this code isn't being used in production. Commented Mar 3, 2013 at 19:14
  • It doesn't matter, because it probably will be in the future Commented Mar 3, 2013 at 19:21

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I understand this, I am just mucking about that's all, learning through trial and error, thanks.
@ShaShads Check the updated example. It should actually work out, as crazy as it would be in production.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.