Can a function be assigned a class variable at runtime in php?

can a function variable be assigned to a class variable at runtime? a kind of "function pointer" like C

something like this: (this will not work, because the amount goes beyond A, but this is the pattern that I have in mind)

 class A {
    public $function_name;
    public functon run($arg1,$arg2){
        $function_name($arg1,$arg2);
    }
}  

function sum($a,$b){
    echo $a+$b;
}

$a=new A();
$a->function_name='sum';

$a->run();     

[edit] I know that there is a "call_user_func", but this is necessary because I understand that I have a function in the scope or using the open class method.

+5
source share
5 answers

You can use an anonymous function if you use PHP> 5.3.0:

$sum = function($a, $b) {
    return $a+$b;
}

$a->function_name = $sum;
+3
source

call_user_func_array:

<?php
class A {

    public $function_name;

    public function run($arg1,$arg2){

        return call_user_func_array( $this->function_name, array($arg1, $arg2 ) );

    }
}  

function sum($a,$b){
    return $a+$b;
}

$a=new A();
$a->function_name= 'sum';

var_dump( $a->run(1,1) ); //2

?>
+2

. , call_user_func. .

<?php
    class A {
        public $function_name;
        public function run($arg1, $arg2) {
        call_user_func($this->function_name, $arg1, $arg2);
        }
    }  

    function sum($a, $b){
        echo $a + $b;
    }

    $a = new A();
    $a->function_name = 'sum';

    $a->run(2, 3);
?>

+1

- ( )

public static function sum($arg1, $arg2)
{
  ..
}

public function run($arg1, $arg2)
{
  $func = $this->function_name;
  $func( $arg1, $arg2);         <-- procedural call
  self::$func($arg1, $arg2);    <-- static method call
}
0

All Articles