PHP Doku:: Liefert Funktionsargumente als Array - function.func-get-args.html

Verlauf / Chronik / History: (14) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenFunction HandlingFunction handling Funktionenfunc_get_args

Ein Service von Reinhard Neidl - Webprogrammierung.

Function handling Funktionen

<<func_get_arg

func_num_args>>

func_get_args

(PHP 4, PHP 5)

func_get_argsLiefert Funktionsargumente als Array

Beschreibung

array func_get_args ( void )

Liefert die der aufrufenden Funktion übergebenen Argumente als Array.

Die Funktion kann zusammen mit func_get_arg() und func_get_args() genutzt werden um Funktionen mit einer variablen Anzahl von Argumenten zu implementieren.

Rückgabewerte

Liefert ein Array mit Kopien aller Argumente mit denen die aufrufende Funktion aufgerufen wurde.

Changelog

Version Beschreibung
5.3.0 Diese Funktion kann nun auch in Parameterlisten genutzt werden.

Fehler/Exceptions

Die Funktion generiert eine Warnung wenn sie außerhalb einer benutzerdefinierten Funktion aufgerufen wird.

Beispiele

Beispiel #1 func_get_args() Beispiel

<?php
function foo()
{
    
$numargs func_num_args();
    echo 
"Anzahl der Argumente: $numargs<br />\n";
    if (
$numargs >= 2) {
        echo 
"Das zweite Argument ist: " func_get_arg(1) . "<br />\n";
    }
    
$arg_list func_get_args();
    for (
$i 0$i $numargs$i++) {
        echo 
"Argument $i ist: " $arg_list[$i] . "<br />\n";
    }
}

foo(123);
?>

Anmerkungen

Hinweis:

Da diese Funktion bei der Ermittlung der Parameterdetails von dem aktuellen Ausführungskontext abhängt, kann sie in PHP-Versionen vor 5.3.0 selbst nicht als Funktionsparameter genutzt werden. Wenn Sie ihre Ergebnisse tatsächlich weitergeben müssen, so müssen Sie diese zunächst einer Variablen zuweisen und dann diese Variable übergeben

Hinweis: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

Siehe auch


23 BenutzerBeiträge:
- Beiträge aktualisieren...
mitko at edabg dot com
6.04.2009 12:48
<?php
/*
This example demonstrate how to use unknown variable arguments by reference.
func_get_args() don't return arguments by reference, but
debug_backtrace() "args" is by reference.
In PHP 5 this have no particular sense, because calling with arguments by reference
is depreciated and produce warning.
*/

class foo {

    var
$bar = "default bar";
   
    function
foo(/*variable arguments*/) {
// func_get_args returns copy of arguments
//        $args = func_get_args();
// debug_backtrace returns arguments by reference           
       
$stack = debug_backtrace();
       
$args = array();
        if (isset(
$stack[0]["args"]))
            for(
$i=0; $i < count($stack[0]["args"]); $i++)
               
$args[$i] = & $stack[0]["args"][$i];
       
call_user_func_array(array(&$this, 'bar'), $args);
    }
   

    function
bar($bar = NULL) {
        if (isset(
$bar))
           
$this->bar = & $bar;
    }
}

$global_bar = "bar global";
$foo = & new foo();
echo
"foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo
"global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    default bar</br>
global_bar:  bar global</br>
*/

$foo = & new foo(&$global_bar);
echo
"foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo
"global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    bar global</br>
global_bar:  new bar</br>
*/

?>
marco @ vi-da
20.03.2009 22:01
sanitazes vars

<?php
function mysql_safe($q) {
   
$x = array_shift(func_get_args());
    return
vsprintf(preg_replace('/%([1-9]):(d|s)/','%$1$$2',$q), array_map('mysql_escape_string',$x));
}
?>

example

<?php
$query
= mysql_safe("select * from somewhere where mood = %2:s and some_id = %1:d order by %3:s desc", $id, 'happy', $order);
?>
Oto Brglez
12.03.2009 15:18
How to create simple sum function that can sum N arguments. Like this:

<?php

function sum(){
   
$s=0;
    foreach(
func_get_args() as $a) $s+= is_numeric($a)?$a:0;
    return
$s;
};

print
sum(1,2,3,4,5,6); // will return 21
print sum(3,2,1); // will return 6
print sum(false,array(),5,5); // will return 10

?>
anderson at francotecnologia dot com
27.08.2008 8:25
How to create a polymorphic/"overloaded" function

<?php
function select()
{
   
$t = '';
   
$args = func_get_args();
    foreach (
$args as &$a) {
       
$t .= gettype($a) . '|';
       
$a = mysql_real_escape_string($a);
    }
    if (
$t != '') {
       
$t = substr($t, 0, - 1);
    }
   
$sql = '';
    switch (
$t) {
        case
'integer':
           
// search by ID
           
$sql = "id = {$args[0]}";
            break;
        case
'string':
           
// search by name
           
$sql = "name LIKE '%{$args[0]}%'";
            break;
        case
'string|integer':
           
// search by name AND status
           
$sql = "name LIKE '%{$args[0]}%' AND status = {$args[1]}";
            break;
        case
'string|integer|integer':
           
// search by name with limit
           
$sql = "name LIKE '%{$args[0]}%' LIMIT {$args[1]},{$args[2]}";
            break;
        default:
           
// :P
           
$sql = '1 = 2';
    }
    return
mysql_query('SELECT * FROM table WHERE ' . $sql);
}
$res = select(29); // by ID
$res = select('Anderson'); // by name
$res = select('Anderson', 1); // by name and status
$res = select('Anderson', 0, 5); // by name with limit
?>
kangaroo232002 at yahoo dot co dot uk
26.08.2008 23:25
Instead of having to define your arg list twice, and keeping to the good style of initialising your variables in the head of your class, you can use (PHP5):

<?php
class myclass {
     public
$value = null;
    public
$key = null;
    public
$column = null;
    public
$table = null;
    public function
__construct() {
       
$vars = get_class_vars();
        for(
$i=0; $i<func_num_args();$i++) {
           
$this->${$vars[$i]}=func_get_arg($i);
        }
    }
}
?>

which should allow you to set variables while retaining their default values if they are not set (in this case, null), without having to mess around with functions to retain default values so is much neater (just don't change the order you declare your vars!)

<?php
//usage
$c = new myclass("value", "tablekey", "tablecol", "table");
echo
$c->key;
//prints 'tablekey'
?>
kentfredric at gmail dot com
1.06.2008 19:55
Re This Note:

Note: Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If this value must be passed, the results should be assigned to a variable, and that variable should be passed.

And In reply to ario [a] mail [dot] utexas [dot] edu

It would appear the code posted by ario is now in fact valid.  ( 5.2.6-pl1-gentoo )

And in fact, the following code works perfectly.
<?php
function foo( $a, $b=null , $c=null )
{
 
var_export(array($a,$b,$c));
}
function
bar()
{
 
foo( func_get_args() );
}
bar( 4,1,2 );
?>
and so does
<?php
foo
( func_get_args() , 1, 2, 3);
?>

It seems the magic is bound to position 1 to let it through.
<?php
function get($a){ return $a; }
function
foo(){
 
var_dump('bar', func_get_args()); // not works
 
var_dump('bar', get( func_get_args()) ); // not this either
 
var_dump(func_get_args(),'bar' ); // this works
 
var_dump(get(func_get_args()),'bar'); // as does this.
}?>
Cool trick that results.
<?php
function cufa( $args, $func ){ return call_user_func_array( $func, $args ); }
function
bar( $a, $b, $c,$d )
{
  
var_dump( $a, $b, $c, $d );
}
function
foo(){ return cufa(func_get_args(), 'bar' ); }
function
baz(){ return cufa(array_merge(func_get_args(),array('baz')), 'bar' ); }
?>
foo( 1,2,3 );
int(1)
int(2)
int(3)
NULL

baz( 3,2,1 );
int(3)
int(2)
int(1)
string(3) "baz"
Anonymous
29.01.2008 5:11
I use the following concept for quick "plugin" of multiple argument support.

<?php

function increment($n) {
 
$p = func_get_args();
  if (
count($p) > 1) {
    return
array_map(__FUNCTION__, $p);
  }
 
$n =& $p[0];
 
  return ++
$n;
}

list(
$two, $three, $four) = increment(1,2,3);

?>
tristan dot colombo at laposte dot net
18.10.2007 10:03
In order to use the function 'func_get_args()' to instanciate differents type of objects, you must use the Reflection API.
By example, we have two different classes and we want to have an unique function (using an unfixed number of parameters) to create the objects. We create two classes 'a' and 'b' where constructors accept different numbers of arguments.
Class a (class/a.class.php):
<?php
 
include_once 'a.class.php';

  class
b extends a
 
{
    private
$param3;

    public function
__construct($a, $b, $c)
    {
     
$this->param1 = $a;
     
$this->param2 = $b;
     
$this->param3 = $c;
    }

    public function
display()
    {
      echo
$this->param1 . ', ' . $this->param2 . ' and ' . $this->param3 . '!<br />';
    }
  }
?>

Class b (class/b.class.php):
<?php

 
class a
 
{
    private
$param1;
    private
$param2;

    public function
__construct($a, $b)
    {
     
$this->param1 = $a;
     
$this->param2 = $b;
    }

    public function
display()
    {
      echo
$this->param1 . ' and ' . $this->param2 . '<br />';
    }
  }
?>

Main program :
<?php

 
function classFactory()
  {
   
// Retrieve arguments list
   
$_args = func_get_args();
   
// Delete the first argument which is the class name
   
$_className = array_shift($_args);

   
// Include the requested class
   
include_once 'class/' . $_className . '.class.php';

   
// Create Reflection object
    // See : http://www.php.net/manual/en/language.oop5.reflection.php
   
$_reflection = new ReflectionClass($_className);

   
// Use the Reflection API
   
return $_reflection->newInstanceArgs($_args);
  }

 
$a = classFactory('a', 'hello', 'world');
 
$b = classFactory('b', 'that\'s', 'all', 'folks');

 
$a->display();
 
$b->display();

?>
gerry+phpnet at buzka dot com
20.09.2007 4:40
If you were having trouble understanding the func_get_default_args() function below, this example should make things more clear. The author of the function could have written it like func_get_expected_default_args() but that doesn't account for args which were passed but not specified in the param list.

example:

<?php
   
function func_get_expected_default_args($a) {
       
// Grab the list of expected arguments.
       
return func_get_args();
    }

    function
func_get_default_args($a) {
       
// Grab the list of expected arguments.
       
$args = array_slice(func_get_args(), 1);

       
// Append any unexpected agruments that may have been also passed
        // to the function, but were not in the param list.
       
return array_merge($args, array_slice($a, count($args)));
    }

    function
foo($bar=5, $foobar=3){
       
$args = func_get_expected_default_args2($bar, $foobar);
        echo
'expected args: '. print_r($args, true);

       
$args = func_get_default_args(func_get_args(), $bar, $foobar);
        echo
'all args: '. print_r($args, true);
    }
   
   
foo(20);

   
foo(20, 95, 'unexpected', 'variables');

   
/*
        Output:

        expected args: Array
        (
            [0] => 20
            [1] => 3
        )
        all args: Array
        (
            [0] => 20
            [1] => 3
        )
        expected args: Array
        (
            [0] => 20
            [1] => 95
        )
        all args: Array
        (
            [0] => 20
            [1] => 95
            [2] => unexpected
            [3] => variables
        )
    */
?>
Sinured
20.08.2007 14:38
It may seem obvious, but if you want your variadic function to at least require one parameter, you can do this instead of checking func_num_args() == 0, which I've seen often:

<?php
function variadic($dummy) {
   
$args = func_get_args();
    foreach (
$args as $arg) {
        echo
"$arg<br />\n";
    }
}
?>

func_get_args() fetches ALL passed parameters, not only those that weren't copied to a local variable.
ario [a] mail [dot] utexas [dot] edu
7.05.2007 23:50
"Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable."

This means that the following code generates an error:

<?php

function foo($list)
{
  echo
implode(', ', $list);
}

function
foo2()
{
 
foo(func_get_args());
}

foo2(1, 2, 3);

?>

However, you can easily get around this by doing the following:

<?php

function foo($list)
{
  echo
implode(', ', $list);
}

function
foo2()
{
 
foo($args = func_get_args());
}

foo2(1, 2, 3);

?>

This captures the context from foo2(), making this legal.  You get the expected output:

"1, 2, 3"
jmcguire81 [at] gmail.com
21.03.2007 23:13
Here is another variation on accepting a variable number of arguments. This allows for a variable number of arguments to be passed to a Class constructor, as well as a customized class version to be used dynamically. Syntax in code is:

<?php
$mail
= Generator("MailClassName", $db_ref);

function
Generator() {

  
$numargs = func_num_args();

  
$classname = func_get_arg(0);
  
$argstring='';
   if (
$numargs > 1) {
     
$arg_list = func_get_args();

      for (
$x=1; $x<$numargs; $x++) {
        
$argstring .= '$arg_list['.$x.']';
         if (
$x != $numargs-1) $argstring .= ',';
      }
   }

   if (
class_exists("Custom{$classname}")) {
     
$classname = "Custom{$classname}";
      if (
$argstring) return eval("return new $classname($argstring);");
      return new
$classname;
   }
  
   if (
$argstring) return eval("return new $classname($argstring);");
   return new
$classname;
}
?>

Hope this is of use to someone.
rafagd at gmail dot com
13.02.2007 17:53
Sometimes, you may need to dynamic set and get of args...

This function merge array args, so you can dynamic set some args by sending an array arg.

<?php
 
function dynamicArgs(/*$arg1, $arg2...$argN*/) {
   
$args = func_get_args(); $num  = func_num_args();
    for (
$i = 1; $i < $num; $i++) {
     
$args[0] = array_merge((array) $args[0], (array) $args[$i]);
    }
    return
$args[0];
  }
 
 
var_dump(dynamicArgs('a',array('b','c'),'d',1);
?>

This should output like:

array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  int(1)
}

1.11.2006 7:26
Same idea as below, but this:

<?php
      
foreach( $args as $k => $v ){
           switch(
$k){
               case
'a':
                  
$this->a= $v; break;
               case
'b':
                  
$this->b= $v; break;
               case
'c':
                  
$this->c= $v; break;
             }
       }
?>

can be shortened to this (as long as all public variables have default values set in their declarations):

<?php
      
foreach( $args as $k=>$v)
            if(isset(
$this->$k)) $this->$k = $v;
?>
kidekat
1.10.2006 15:02
To pass named arguments in a Perl fashion through class constructors, I use this:

<?php
class Test{

   
// set class defaults for values not assigned by constructor
   
public $a = 0;
    public
$b = 'string';
    public
$c = array();

    public function
__construct( $args = array() ) {

       
// parse tagged arguments in Perl fashion
       
foreach( $args as $k => $v ){
            switch(
$k){
                case
'a':
                   
$this->a= $v; break;
                case
'b':
                   
$this->b= $v; break;
                case
'c':
                   
$this->c= $v; break;
             }
        }
    }

}

$t = new Test(  array( 'b'=>'new value', 'c'=>array(1,'test') ) );
?>

This allows $a to keep its default of 0, while $b gets reassigned to 'new value' and $c becomes the array(1,'test'). The catch is that you add O(n^2) "big-O notation" to the begging of every class constructor which becomes expensive on "larger" classes. While arguments defaults like the following have only O(n) "constant" amount of work.

<?php
   
public funciton __construct( $a=0, $b='string', $c=array()){ ... }
?>
bew
31.03.2006 17:55
A more concise way of expressing my idea from the previous post (I'd forgotten about array_slice()):

<?php
function func_get_default_args($a) {
   
$args = array_slice(func_get_args(), 1);
    return
array_merge($args, array_slice($a, sizeof($args)));
}

function
foo($a = 1, $b = 2, $c = 3) {
   
print_r(func_get_default_args(func_get_args(), $a, $b, $c));
}

// prints: Array ( [0] => a [1] => b [2] => 3 )
foo('a', 'b');
?>
Nathan Ostgard
6.12.2005 19:14
If you're using PHP5, the variable number of argument functions all return the objects by reference - and not a copy of the object, as this leads you to believe.
robert at defore dot st
15.02.2005 9:47
<?php
# Another attempt at named args (perl-inspired):

# list_to_assoc('key', 'value', 'key', 'value', ...) =>
#     pairs[]
function list_to_assoc() {
   
$list = func_get_args();
   
$assoc = array();

    while (
$list and count($list) > 1) {
       
$assoc[array_shift($list)] = array_shift($list);
    }

    if (
$list) { $assoc[] = $list[0]; }

    return
$assoc;
}

# Usage:

function example($required) {
   
$args = func_get_args(); array_shift($args); # drop 'required'
   
$rest = list_to_assoc($args);
    echo
"$required\n" . $rest['comment'];
}
?>

example("This is required...",
        'comment', 'this is not.'); # this is like 'comment' => 'this is not'
T.M.
4.11.2004 16:24
Simple function to calculate average value using dynamic arguments:
<?php
function average(){
    return
array_sum(func_get_args())/func_num_args();
}
print
average(10, 15, 20, 25); // 17.5
?>
volte6 at drunkduck dot com
30.09.2004 23:54
For those who have a use for a C style enum() function:

<?php
//*******************************************
// void enum();
// enumerates constants for unique values guarenteed.
function enum()
{
 
$i=0;
 
$ARG_ARR = func_get_args();
  if (
is_array($ARG_ARR))
  {
    foreach (
$ARG_ARR as $CONSTANT)
    {
     
define ($CONSTANT, ++$i);
    }
  }
}

// USAGE:
enum(ERR_USER_EXISTS, ERR_OLD_POST);

// etc. etc.
//*******************************************
?>


this can be used for error codes etc.
I deliberately skipped the 0 (zero) define, which could be useful for error checking.
mark at manngo dot net
24.03.2003 8:13
You can also fake named arguments using eval:

<?php
function test()
{   foreach (
func_get_args() as $k=>$arg) eval ("\$$arg;");
    echo
"$a plus $b gives ".($a+$b);
}

test("a=3","b=4");
?>
daveNO at ovumSPAMdesign dot com
18.09.2001 8:29
<?php
// How to simulate named parameters in PHP.
// By Dave Benjamin <dave@ovumdesign.com>

// Turns the array returned by func_get_args() into an array of name/value
// pairs that can be processed by extract().
function varargs($args) {
   
$count = count($args);
    for (
$i = 0; $i < $count; $i += 2) {
       
$result[$args[$i]] = $args[$i + 1];
    }
   
    return
$result;
}

// Example
function test(&$ref1, &$ref2) {
   
// Default arguments go here.
   
$foo = "oof";
   
   
// Do some magic.
   
extract(varargs(func_get_args()));

    echo
nl2br("\n\$var1 = $var1");
    echo
nl2br("\n\$var2 = $var2");
    echo
nl2br("\n\$foo = $foo\n\n");
   
   
// Modify some variables that were passed by reference.
    // Note that func_get_args() doesn't pass references, so they
    // need to be explicitly declared in the function definition.
   
$ref1 = 42;
   
$ref2 = 84;
}

$a = 5;
$b = 6;

echo
nl2br("Before calling test(): \$a = $a\n");
echo
nl2br("Before calling test(): \$b = $b\n");

// Try removing the 'foo, "bar"' from the following line.
test($a, $b, var1, "abc", var2, "def", foo, "bar");

echo
nl2br("After calling test(): \$a = $a\n");
echo
nl2br("After calling test(): \$b = $b\n");
?>

4.06.2001 16:44
You can pass a variable number of arguments to a function whilst keeping references intact by using an array. The disadvantage of course, is that the called function needs to be aware that it's arguments are in an array.

<?php
// Prints "hello mutated world"
function mutator($args=null) {
$n=count($args);
while(
$i<$n) $args[$i++] = "mutated";
}
$a = "hello";
$b = "strange";
$c = "world";
mutator(array($a, &$b, $c));
echo
"$a $b $c";
?>



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",...)