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
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.
$name() first?display().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([$book, $name], ... $argsArray);
$book->$name? what was the error?()from$name