简体   繁体   中英

PHP - How to call another function in a class dynamically

My PHP codes :

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";
    }

}

When i use FrontEndController->Modules('product'); i want it return value from Mod_product() , so also when I use FrontEndController->Modules('promo'); it will return value from Mod_promo() . How to do this?

Use method_exists :

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

    $function = $prefix.$param;

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

You have a few mistakes in your code:

function_exists does not work for classes, use method_exists instead.

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

This does not work either, use call_user_func instead.

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

Corrected code:

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";
    }

}

Update your Modules function like this

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

Hope it helps :)

The Reflection Class is the ideal tool for this. It's a Swiss army knife for classes.

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;      
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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