Call a PHP function dynamically

后端 未结 6 1396
[愿得一人]
[愿得一人] 2020-12-18 19:22

Is there a way to call a function through variables?

For instance, I want to call the function Login(). Can I do this:

$varFunction = \"Login\"; //to         


        
6条回答
  •  借酒劲吻你
    2020-12-18 20:01

    If it's in the same class:

    $funcName = 'Login';
    
    // Without arguments:
    $this->$funcName();
    
    // With arguments:
    $this->$funcName($arg1, $arg2);
    
    // Also acceptable:
    $this->{$funcName}($arg1, $arg2)
    

    If it's in a different class:

    $someClass = new SomeClass(); // create new if it doesn't already exist in a variable
    $someClass->$funcName($arg1, $arg2);
    
    // Also acceptable:
    $someClass->{$funcName}($arg1, $arg2)
    

    Tip:

    If the function name is dynamic as well:

    $step = 2;
    
    $this->{'handleStep' . $step}($arg1, $arg2);
    // or
    $someClass->{'handleStep' . $step}($arg1, $arg2);
    

    This will call handleStep1(), handleStep2(), etc. depending on the value of $step.

提交回复
热议问题