0

For a project I'm working on, I'm trying to call a method using a property

$this->action = "home";
$action = $this->action;
$this->$action();

Is there a shorter way to do this? I tried the following, but it won't work:

$this->action = "home";
$this->$this->action();

So I want to set the $action property, and then call the method that has the same name as $action.

0

2 Answers 2

3

This is probably what you want:

$this->action = "home";
$this->{$this->action}();

This works with methods and properties. $objref->{ [expression] } is the same as $objref->hello if the [expression] evaluates to hello.

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

1 Comment

Rereading his question and your response I understand what he was after. Good solution here.
0

Look into the call_user_func function.

Untested, but it may look something like this:

call_user_func($this->action);

2 Comments

call_user_func(array($this,$this->action)); surely
This could work too. If you want to call an instance method you have to supply an array with the object instance too (see callbacks for more on that). That would look like call_user_func(array($this, $this->action));

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.