PHP 7.1.0 Released

Fonctions variables

PHP supporte le concept de fonctions variables. Cela signifie que si le nom d'une variable est suivi de parenthèses, PHP recherchera une fonction de même nom, et essaiera de l'exécuter. Cela peut servir, entre autres, pour faire des fonctions de rappel, des tables de fonctions...

Les fonctions variables ne peuvent pas fonctionner avec les éléments de langage comme les echo, print, unset(), isset(), empty(), include, require etc. Vous devez utiliser votre propre gestion de fonctions pour utiliser un de ces éléments de langages comme fonctions variables.

Exemple #1 Exemple de fonction variable

<?php
function foo() {
    echo 
"dans foo()<br />\n";
}

function 
bar($arg '')
{
    echo 
"Dans bar(); l'argument était '$arg'.<br />\n";
}

// Ceci est une fonction détournée de echo
function echoit($string)
{
    echo 
$string;
}

$func 'foo';
$func();        // Appel foo()

$func 'bar';
$func('test');  // Appel bar()

$func 'echoit';
$func('test');  // Appel echoit()
?>

Vous pouvez aussi appeler les méthodes d'un objet en utilisant le système des fonctions variables.

Exemple #2 Exemple de méthode variable

<?php
class Foo
{
    function 
Variable()
    {
        
$name 'Bar';
        
$this->$name(); // Appelle la méthode Bar()
    
}
    
    function 
Bar()
    {
        echo 
"C'est Bar";
    }
}

$foo = new Foo();
$funcname "Variable";
$foo->$funcname();  // Appelle $foo->Variable()

?>

Lors de l'appel à des méthodes statiques, l'appel fonction est meilleur que l'opérateur de propriété statique :

Exemple #3 Exemple de méthode variable avec des propriétés statiques

<?php
class Foo
{
    static 
$variable 'static property';
    static function 
Variable()
    {
        echo 
'Method Variable called';
    }
}

echo 
Foo::$variable// Ceci affiche 'static property'. Il est nécessaire d'avoir une $variable dans le contexte.
$variable "Variable";
Foo::$variable();  // Ceci appelle $foo->Variable(), lisant ainsi la $variable depuis le contexte.

?>

Depuis PHP 5.4.0, vous pouvez appeler n'importe quel callable stocké dans une variable.

Exemple #4 callables complexe

<?php
class Foo
{
    static function 
bar()
    {
        echo 
"bar\n";
    }
    function 
baz()
    {
        echo 
"baz\n";
    }
}

$func = array("Foo""bar");
$func(); // Affiche "bar"
$func = array(new Foo"baz");
$func(); // Affiche "baz"
$func "Foo::bar";
$func(); // Affiche "bar" depuis PHP 7.0.0; avant, émettait une fatal error

Voir aussi is_callable(), call_user_func(), les variables variables et function_exists().

Historique

Version Description
7.0.0 'ClassName::methodName' est autorisée comme fonction variable.
5.4.0 Les tableaux, qui sont des callables valides, sont autorisés comme fonctions variables .

add a note add a note

User Contributed Notes 11 notes

up
38
Anonymous
1 year ago
i'm not sure, but simple mistake in this place ($f instead $func):
<?php
$func
= array("Foo", "bar");
$func(); // prints "bar"
$f = array(new Foo, "baz");
$func(); // prints "baz"
$f = "Foo::bar";
$func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
?>
up
12
Anonymous
5 years ago
$ wget http://www.php.net/get/php_manual_en.tar.gz/from/a/mirror
$ grep -l "\$\.\.\." php-chunked-xhtml/function.*.html

List of functions that accept variable arguments.
<?php
array_diff_assoc
()
array_diff_key()
array_diff_uassoc()
array()
array_intersect_ukey()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_push()
array_replace()
array_replace_recursive()
array_unshift()
call_user_func()
call_user_method()
compact()
dba_open()
dba_popen()
echo()
forward_static_call()
fprintf()
fscanf()
httprequestpool_construct()
ibase_execute()
ibase_set_event_handler()
ibase_wait_event()
isset()
list()
maxdb_stmt_bind_param()
maxdb_stmt_bind_result()
mb_convert_variables()
newt_checkbox_tree_add_item()
newt_grid_h_close_stacked()
newt_grid_h_stacked()
newt_grid_v_close_stacked()
newt_grid_v_stacked()
newt_win_choice()
newt_win_entries()
newt_win_menu()
newt_win_message()
newt_win_ternary()
pack()
printf()
register_shutdown_function()
register_tick_function()
session_register()
setlocale()
sprintf()
sscanf()
unset()
var_dump()
w32api_deftype()
w32api_init_dtype()
w32api_invoke_function()
wddx_add_vars()
wddx_serialize_vars()
?>
up
1
Lenix
3 months ago
A Variable method example:

<?php
class hello
{
    private
$funcname='myfunc';
    public function
run()
    {
       
$var=$this->funcname;
       
$this->$var();
    }

    public function
myfunc()
    {
        echo
"Hello World!";
    }
}

$run=new hello();
$run->run();
?>
up
-7
ian at NO_SPAM dot verteron dot net
13 years ago
A good method to pass around variables containing function names within some class is to use the same method as the developers use in preg_replace_callback - with arrays containing an instance of the class and the function name itself.

function call_within_an_object($fun)
{
  if(is_array($fun))
  {
    /* call a function within an object */
    $fun[0]->{$fun[1]}();
  }
  else
  {
    /* call some other function */
    $fun();
  }
}

function some_other_fun()
{
  /* code */
}

class x
{
  function fun($value)
  {
    /* some code */
  }
}

$x = new x();

/* the following line calls $x->fun() */
call_within_an_object(Array($x, 'fun'));

/* the following line calls some_other_fun() */
call_within_an_object('some_other_fun');
up
-7
boards at gmail dot com
10 years ago
If you want to call a static function (PHP5) in a variable method:

Make an array of two entries where the 0th entry is the name of the class to be invoked ('self' and 'parent' work as well) and the 1st entry is the name of the function.  Basically, a 'callback' variable is either a string (the name of the function) or an array (0 => 'className', 1 => 'functionName').

Then, to call that function, you can use either call_user_func() or call_user_func_array().  Examples:

<?php
class A {

  protected
$a;
  protected
$c;

  function
__construct() {
   
$this->a = array('self', 'a');
   
$this->c = array('self', 'c');
  }

  static function
a($name, &$value) {
    echo
$name,' => ',$value++,"\n";
  }

  function
b($name, &$value) {
   
call_user_func_array($this->a, array($name, &$value));
  }

  static function
c($str) {
    echo
$str,"\n";
  }

  function
d() {
   
call_user_func_array($this->c, func_get_args());
  }

  function
e() {
   
call_user_func($this->c, func_get_arg(0));
  }

}

class
B extends A {

  function
__construct() {
   
$this->a = array('parent', 'a');
   
$this->c = array('self', 'c');
  }

  static function
c() {
   
print_r(func_get_args());
  }

  function
d() {
   
call_user_func_array($this->c, func_get_args());
  }

  function
e() {
   
call_user_func($this->c, func_get_args());
  }

}

$a =& new A;
$b =& new B;
$i = 0;

A::a('index', $i);
$a->b('index', $i);

$a->c('string');
$a->d('string');
$a->e('string');

# etc.
?>
up
-7
madeinlisboa at yahoo dot com
14 years ago
Finally, a very easy way to call a variable method in a class:

Example of a class:

class Print() {
    var $mPrintFunction;

    function Print($where_to) {
        $this->mPrintFunction = "PrintTo$where_to";
    }

    function PrintToScreen($content) {
        echo $content;
    }

    function PrintToFile($content) {
        fputs ($file, $contents);
    }

.. .. ..

    // first, function name is parsed, then function is called
    $this->{$this->mPrintFunction}("something to print");
}
up
-7
msmith at pmcc dot com
14 years ago
Try the call_user_func() function.  I find it's a bit simpler to implement, and at very least makes your code a bit more readable... much more readable and simpler to research for someone who isn't familiar with this construct.
up
-3
josh at joshstroup dot xyz
7 months ago
A small, but helpful note. If you are trying to call a static function from a different namespace, you must use the fully qualified namespace, even if they have the same top level namespace(s). For example if you have the following class to call:

<?php
namespace Project\TestClass;
class
Test {
    static function
funcToCall() {
        return
"test";
    }
}
?>
You must call it as:
<?php
namespace Project\OtherTestClass;
class
OtherTest {
    static function
callOtherFunc() {
       
$func = '\Project\TestClass::funcToCall';
       
$func();
    }
}
?>
and not:
<?php
class OtherTest {
    static function
callOtherFunc() {
       
$func = 'TestClass::funcToCall';
       
$func();
    }
}
?>
up
-11
Storm
11 years ago
This can quite useful for a dynamic database class:

(Note: This just a simplified section)

<?php
class db {

    private
$host = 'localhost';
    private
$user = 'username';
    private
$pass = 'password';
    private
$type = 'mysqli';
   
    public
$lid = 0;

   
// Connection function
   
function connect() {
       
$connect = $this->type.'_connect';
           
        if (!
$this->lid = $connect($this->host, $this->user, $this->pass)) {
            die(
'Unable to connect.');
        }
}
}
$db  = new db;
$db->connect();
?>

Much easier than having multiple database classes or even extending a base class.
up
-20
AnonymousPoster at disposeamail dot com
6 years ago
Variable functions allows higher-order programming.

Here is the classical map example.

<?php
/*
* Map function. At each $element of the $list, calls $fun([$arg1,[$arg2,[...,]],$element,$accumulator),
*      stores the return value into $accumulator for the next loop. Returns the last return value of the function,
*
* Notes : uses call_user_func_array() so passing parameters doesn't depend on $fun signature
*          It also returns FALSE upon error.
*          Please check the php documentation for more information
*/
function map($fun, $list,$params=array()){
   
$acc=NULL;
   
$last=array_push($params, NULL,$acc)-1; // alloc $element and $acc at the end
   
foreach($list as $params[$last-1]){
       
$params[$last]=call_user_func_array($fun , $params  );
    }
   
$acc=array_pop($params);
    return
$acc;
}

function
add($element,$acc){ // maybe only with multi-length function
   
if ($acc == NULL);
    return
$acc=$element+$acc;
}

$result=0;
$result=addTo($result,1);
$result=addTo($result,2);
$result=addTo($result,3);
echo
"result = $result\n";

$result=0;
$result=map('addTo',array(1,2,3));
echo
"result= $result\n";
?>
up
-25
imurnane at internode on net
5 years ago
Create and call a dynamically named function

<?php
$tmp
= "foo";
$
$tmp = function() {
    global
$tmp;
    echo
$tmp;
};

$
$tmp();
?>

Outputs "foo"
To Top