Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 815
Zorb Avatar asked Dec 16 '11 18:12

Zorb


People also ask

Can we store a function in a variable in PHP?

Variable functions ¶PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it.

How can use variable in one function in another PHP?

You need to instantiate (create) $newVar outside of the function first. Then it will be view-able by your other function. You see, scope determines what objects can be seen other objects. If you create a variable within a function, it will only be usable from within that function.

How to define variable in class in PHP?

The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.


2 Answers

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

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

$a->function_name = $sum;
like image 196
Eric Avatar answered Sep 20 '22 11:09

Eric


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

?>
like image 27
Esailija Avatar answered Sep 18 '22 11:09

Esailija