0

I have a method display() in the book class.

$name = 'display()';
$book = new Book('PHP Object-Oriented Solutions', 300);

$book->$name;

How can i call display method using $book->$name

7
  • Did you try $book->$name? what was the error? Commented Dec 6, 2016 at 10:29
  • 4
    I'm voting to close this question as off-topic because it is a duplicate of the PHP Manual. php.net/manual/en/functions.variable-functions.php Commented Dec 6, 2016 at 10:29
  • when I use $book->$name it says Notice: Undefined property: Book::$display() Commented Dec 6, 2016 at 10:32
  • Remove () from $name Commented Dec 6, 2016 at 10:32
  • Removing () from $name gives Undefined property: Book::$display Commented Dec 6, 2016 at 10:34

2 Answers 2

3

You need to tell PHP that you're trying to execute a method, not in the variable itself, but within the actual code:

$name = 'display';
$book = new Book('PHP Object-Oriented Solutions', 300);

$book->$name();

Otherwise, as you have seen, it will treat $name as a property name, and rightly so ... If you have both a property and a method named 'display', there wouldn't be a way to distinguish between the two using what you've tried.

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

3 Comments

Isn't that going to run the $name() first?
No, the lexer sees the OOP context and would ignore a regular function named display().
wasn't sure about it and kind of couldn't test it :)
0

The cleanest way (imo at least) is to use something like:

$name = 'display';
$book = new Book('PHP Object-Oriented Solutions', 300);

call_user_func([$book, $name]); // This looks cleaner and/or more obvious on first sight.
// call_user_func_array([$book, $name], $arrayOfArguments);

// And as @Narf suggested (and I agree cuz we move forward)
call_user_func([$book, $name], ... $arrayOfArguments);

And yes you can pass parameters to this function, that will be passed to the function, but you have to list them after the callable array. in order to avoid doing that (hard to maintain and not always what you want) you can use call_user_func_array which accepts an array of arguments as second argument that is passed to the callable.

call_user_func Documentation

call_user_func_array Documentation

3 Comments

Argument unpacking FTW: call_user_func([$book, $name], ... $argsArray);
~Lol, that is if we are throwing 5.6 out the window (not mentioning others since EOL), but will edit~ Apparently I am dumb enough to forget they are 5.6 feature ... facepalm
That's a PHP 5.6 feature. ;) The EOLd versions can RIP.

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.