简体   繁体   English

PHP oop如何调用动态函数名称

[英]PHP oop how can i call dynamic function name

I have a method display() in the book class. 我在书本类中有一个方法display()

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

$book->$name;

How can i call display method using $book->$name 如何使用$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: 您需要告诉PHP您正在尝试执行一种方法,而不是在变量本身中,而是在实际代码中:

$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作为属性名,这是正确的......如果你同时拥有一个属性,一个名为“显示”方法不会有使用两者区分开的方式您尝试过的。

The cleanest way (imo at least) is to use something like: 最干净的方法(至少是imo)是使用类似以下内容的方法:

$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_array ,该方法接受参数数组作为传递给可调用对象的第二个参数。

call_user_func Documentation call_user_func文档

call_user_func_array Documentation call_user_func_array文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM