it is possible to assign a function to a class variable at runtime in php?

Zorb Source

it is possible to assign to a class variable a function at runtime to be executed? a kind of "function pointer" like C

something like this: (this won't work because sum is out of the scope of A, but this is the pattern i mean)

 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 there is "call_user_func" but it need as i understand to have the function in the scope or use a public class method

phpfunction-pointers

Answers

answered 7 years ago Esailija #1

Using 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

?>

answered 7 years ago Alex Turpin #2

It works regardless of scope. You just gotta call it using call_user_func. I also fixed a couple of typos in your example.

<?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);
?>

Live example

answered 7 years ago Eric #3

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

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

$a->function_name = $sum;

answered 7 years ago ajreal #4

Another way is to make use variable variables (applicable to object method)

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
}

answered 7 years ago goat #5

Use any variation of the Callback pseudo type. Use it with call_user_func or call_user_func_array

The manual gives great examples of usage for the above.

Also see the new php 5.4 Closure::bindTO method if you want to be able to easily use the $this keyword in it.

comments powered by Disqus