[英]Calling PHP functions dynamically?
Don't know if I worded the question right, but basically what I want to know is if there is an easier (shorter) way of doing the following: 不知道我的措词是否正确,但基本上我想知道的是,是否存在一种更简便(更短)的方法来进行以下操作:
switch( $type ) {
case 'select': $echo = $this->__jw_select( $args ); break;
case 'checkbox': $echo = $this->__jw_checkbox( $args ); break;
case 'radio': $echo = $this->__jw_radio( $args ); break;
case 'input': $echo = $this->__jw_input( $args ); break;
case 'textarea': $echo = $this->__jw_textarea( $args ); break;
default: return null;
}
Is there any way I could do something like $echo = $this->__jw_{$type}( $args );
有什么办法可以像
$echo = $this->__jw_{$type}( $args );
这样吗$echo = $this->__jw_{$type}( $args );
? ? I tried this code but of course, it failed.
我尝试了这段代码,但是当然失败了。 Any ideas?
有任何想法吗?
Try this: 尝试这个:
$method = "__jq_$type";
$echo = $this->$method($args);
Alternatively, use call_user_func
: 或者,使用
call_user_func
:
$method = "__jq_$type";
$echo = call_user_func(array($this, $method), $args);
Of course, there's no validation on the method name here. 当然,这里没有方法名称的验证。
There are many ways you could do it, here's one: 您可以通过多种方式来实现,这是一种:
if(method_exists($this, "__jw_$type"))
{
$echo = $this->{"__jw_$type"}($args);
}
$action = "__jw__$type";
$this->$action($args);
Of course, you'll really want to verify that $type
is an allowed type. 当然,您将真的要验证
$type
是允许的类型。
$field = "__jw_$type";
$echo = $this->{$field}($args);
or even more simply, 或更简单地说,
$echo = $this->{"__jw_$type"}($args);
You can try something like this: 您可以尝试如下操作:
$type = '__jw_'.$type;
if(method_exists($type,$this))
$this->{$type}($args);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.