繁体   English   中英

PHP - 如何动态调用类中的另一个函数

[英]PHP - How to call another function in a class dynamically

我的PHP代码:

class FrontEndController extends BaseController {

    public function Welcome()
    {
        return View::make('frontend.index');
    }

    public function Modules($param="")
    {
        /* convert parameter "$param" be a function */      
        $prefix = "Mod_";  // func prefix's
        if (function_exists($this->$prefix.$param)) {
            return $this->$prefix.$param();
        }else
        {
            return $param;      
        }
    }

    protected function Mod_product(){
        return "You are called CATEGORY";
    }
    protected function Mod_promo(){
        return "You are called PROMO";
    }

}

当我使用FrontEndController->Modules('product'); 我希望它从Mod_product()返回值,所以当我使用FrontEndController->Modules('promo'); 它将从Mod_promo()返回值。 这个怎么做?

使用method_exists

    $prefix = "Mod_";  // func prefix's

    $function = $prefix.$param;

    if ( method_exists( $this, $function ) ) {      
        return $this->$function();      
    } else {
        return $param;      
    }

您的代码中有一些错误:

function_exists不适用于类,而是使用method_exists

if (function_exists($this->$prefix.$param)) {

这也不起作用,改为使用call_user_func

return $this->$prefix.$param();

更正代码:

class FrontEndController extends BaseController {

    public function Welcome()
    {
        return View::make('frontend.index');
    }

    public function Modules($param="")
    {
        /* convert parameter "$param" be a function */      
        $prefix = "Mod_";  // func prefix's
        $fcn = $prefix.$param; // save name of function

        if (method_exists($this, $fcn)) {
            return call_user_func(array($this, $fcn));
        }else
        {
            return $param;      
        }
    }

    protected function Mod_product(){
        return "You are called CATEGORY";
    }
    protected function Mod_promo(){
        return "You are called PROMO";
    }

}

像这样更新您的模块功能

$this->{$prefix . $params}();

希望能帮助到你 :)

反射类是理想的工具。 这是一把瑞士军刀。

public function Modules($param="")
{
    /* convert parameter "$param" be a function */      
    $prefix = "Mod_";  // func prefix's
    $reflection = new ReflectionClass(__CLASS__);
    if($reflection->hasMethod($prefix.$param)) {
        return $this->$prefix.$param();
    }else
    {
        return $param;      
    }
}

暂无
暂无

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

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