Griff
Griff

Reputation: 1747

Calling a classes method from same classes property syntax? PHP

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

Upvotes: 0

Views: 84

Answers (1)

lll
lll

Reputation: 12889

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()}();

Upvotes: 1

Related Questions