PHP Doku:: Variablenfunktionen - functions.variable-functions.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchSprachreferenzFunktionenVariablenfunktionen

Ein Service von Reinhard Neidl - Webprogrammierung.

Funktionen

<<Rückgabewerte

Interne (eingebaute) Funktionen>>

Variablenfunktionen

PHP unterstützt das Konzept der Variablenfunktionen. Wenn Sie an das Ende einer Variablen Klammern hängen, versucht PHP eine Funktion aufzurufen, deren Name der aktuelle Wert der Variablen ist. Dies kann unter anderem für Callbacks, Funktionstabellen, usw. genutzt werden.

Variablenfunktionen funktionieren nicht mit Sprachkonstrukten wie echo(), print(), unset(), isset(), empty(), include() und require(). Sie müssen Ihre eigenen Wrapperfunktionen verwenden, um diese Konstrukte als variable Funktionen benutzen zu können.

Beispiel #1 Beispiel für Variablenfunktionen

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

function 
bar($arg '')
{
    echo 
"In bar(); der Parameter ist '$arg'.<br />\n";
}

// Dies ist eine Wrapperfunkiton für echo
function echoit($string)
{
    echo 
$string;
}

$func 'foo';
$func();        // Dies ruft foo() auf

$func 'bar';
$func('test');  // Dies ruft bar() auf

$func 'echoit';
$func('test');  // Dies ruft echoit() auf
?>

Sie können auch die Methode eines Objektes mittels der variablen Funktionen aufrufen.

Beispiel #2 Variable Methode

<?php
class Foo
{
    function 
Variable()
    {
        
$name 'Bar';
        
$this->$name(); // Dies ruft die Bar() Methode auf
    
}

    function 
Bar()
    {
        echo 
"Das ist Bar";
    }
}

$foo = new Foo();
$funcname "Variable";
$foo->$funcname();   // Dies ruft $foo->Variable() auf

?>

Siehe auch call_user_func(), Variable Variablen und function_exists().


8 BenutzerBeiträge:
- Beiträge aktualisieren...
AnonymousPoster at disposeamail dot com
3.05.2010 23:20
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";
?>
boards at gmail dot com
22.01.2006 19:07
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.
?>
Storm
3.05.2005 17:34
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.
ian at NO_SPAM dot verteron dot net
20.12.2002 16:33
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');
madeinlisboa at yahoo dot com
5.09.2002 14:14
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");
}
msmith at pmcc dot com
3.05.2002 1:49
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.
anpatel at NOSPAM_cbu dot edu
18.03.2002 6:11
Yes interpolation can be very tricky. I suggest that you always use parenthesis, or curly brackets(whichever applies) to make your expression clear.

Dont ever depend on a language's expression parse preference order.
retro at enx dot org
14.01.2002 4:18
Another way to have php parse a variable within an object as a function is to simply set a temporary variable to its value. For example:

$obj->myfunction = "foo";
$x = $obj->myfunction;
$x(); // calls the function named "foo"



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)