0

In php reading from here

http://docs.php.net/manual/en/migration54.new-features.php

It says,

Class member access on instantiation has been added, e.g. (new Foo)->bar().

I have a class and call its methods like below (as I cannot do what it says above!!),

$router = new RouterCore();
$method = $router->method;
$controller = new $router->controller();
$controller->$method();

What is the syntax for doing what is stated above when both of the class name and the method name exist as properties of another class? I have tried what is below;

$router = new RouterCore();
new ($router->controller())->$router->method(); // no go
new $router->controller()->$router->method(); // no go
new ($router->controller()->$router->method()); // no go

1 Answer 1

1

You're not following the syntax from the documentation.

new ($router->controller())->$router->method();

is not the same as

(new $router->controller())->$router->method();

In the first instance you are trying to perform new on the result of method(), however the second instance creates a new object from the result of controller() and then calls it's method.

Even then $router is not going to be a property of the controller, you need to evaluate $router->method() first and then use that as the method name.

I suspect what you actually want is

(new $router->controller())->{$router->method()}();

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you what I wanted was very close to what you said it was, (new $this->controller())->{$this->method}();, will accept when I can, was a very simple mistake to make had me stumped for about half an hour, the joy of programming :p
Is there any documentation on using the curly braces I have never seen it done before and would like to read up on it?
@Griff Sure it's hidden in the String documentation under variable parsing.

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.