[英]How to use a variable to call a function in PHP?
is it possible to do something like this in php? 是否有可能在php中做类似的事情?
$this->getUser$number(); $ this-> getUser $ number();
I can't find if there's somekinda syntax to make this possible. 我找不到是否有某种语法使之成为可能。
Regards 问候
Yes, there is: 就在这里:
$this->{"getUser".$number}();
Of course you can use the same syntax outside a method: 当然,您可以在方法外使用相同的语法:
$obj = new Something();
$obj->{"getUser".$number}();
That said, code like this is a bad smell and should be avoided. 就是说,这样的代码是难闻的气味,应避免使用。 For example, it's better to make the
getUser
method accept an argument and call it like this: 例如,最好使
getUser
方法接受一个参数并这样调用它:
$this->getUser($number);
This way the call site remains "sane", while the implementation of getUser
can use $number
as eg an index into an array and also achieve much better clarity. 这样,调用站点将保持“理智”,而
getUser
的实现可以使用$number
作为例如数组的索引,并且还可以获得更好的清晰度。
It's called OOP programming, it is used in most likely any big system. 这称为OOP编程,它很可能在任何大型系统中使用。 It is also used alot in a MVC application.
它还在MVC应用程序中大量使用。 Read more about OOP programming here;
在此处阅读有关OOP编程的更多信息; http://www.php.net//manual/en/language.oop5.php
http://www.php.net//manual/zh/language.oop5.php
These expression can also be used like this; 这些表达式也可以这样使用:
$this->$name
or even further to; 甚至进一步
$this->name =& $name
$this->name = $${val}
It is not possible to use symbol $
as name of function. 不能将符号
$
用作功能名称。 But on the other hand $this->getUserNumber();
但是另一方面,
$this->getUserNumber();
you can use inside some class. 您可以在某些类中使用。
You can also do this as 您也可以这样做
$number = "10";
$func = "getUser".$number ;
$this->$func();
it'll call some function named 它会调用一些名为
getUser10();
getUser10();
Yes you can do this: 是的,您可以这样做:
$methodName = 'getUser' . $number;
$this->$methodName();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.