簡體   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