func_get_args

(PHP 4, PHP 5, PHP 7, PHP 8)

func_get_argsDevuelve un array que se compone de una lista de argumentos de función

Descripción

func_get_args(): array

Obtiene un array de la lista de argumentos de una función.

Esta función se puede usar junto con func_get_arg() y func_num_args() para permitir a las funciones definidas por el usuario aceptar una lista de argumentos de longitud variable.

Valores devueltos

Devuelve un array en el que cada elemento es una copia del miembro correspondiente de la lista de argumentos de la función definida por el usuario.

Historial de cambios

Versión Descripción
5.3.0 Esta función ahora se puede usar en listas de parámetros.
5.3.0 Si esta función es llamada desde el ámbito último de un archivo que ha sido incluido mediante una llamada a include o require desde dentro de una función en el archivo de llamada, ahora genera una advertencia y devuelve false.

Errores/Excepciones

Genera una advertencia si se llama desde fuera de una función definida por el usuario.

Ejemplos

Ejemplo #1 Ejemplo de func_get_args()

<?php
function foo()
{
    
$númargs func_num_args();
    echo 
"Número de argumentos: $númargs \n";
    if (
$númargs >= 2) {
        echo 
"El segundo argumento es: " func_get_arg(1) . "\n";
    }
    
$arg_list func_get_args();
    for (
$i 0$i $númargs$i++) {
        echo 
"El argumento $i es: " $arg_list[$i] . "\n";
    }
}

foo(123);
?>

El resultado del ejemplo sería:

Número de argumentos: 3
El segundo argumento es: 2
El argumento 0 es: 1
El argumento 1 es: 2
El argumento 2 es: 3

Ejemplo #2 Ejemplo de func_get_args() antes y después de PHP 5.3

prueba.php
<?php
function foo() {
    include 
'./fga.inc';
}

foo('Primer argumento''Segundo argumento');
?>

fga.inc
<?php

$args 
func_get_args();
var_export($args);

?>

Salida antes de PHP 5.3:

array (
  0 => 'Primer argumento',
  1 => 'Segundo argumento',
)

Salida en PHP 5.3 y posterior:

Warning: func_get_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Ejemplo #3 func_get_args() ejemplo de argumentos byref (pasa un objeto como referencia) y byval (pasa un objeto como valor)

<?php
function byVal($arg) {
    echo 
'Pasó como     : 'var_export(func_get_args()), PHP_EOL;
    
$arg 'baz';
    echo 
'Tras el cambio  : 'var_export(func_get_args()), PHP_EOL;
}

function 
byRef(&$arg) {
    echo 
'Pasó como     : 'var_export(func_get_args()), PHP_EOL;
    
$arg 'baz';
    echo 
'Tras el cambio  : 'var_export(func_get_args()), PHP_EOL;
}

$arg 'bar';
byVal($arg);
byRef($arg);
?>

Salida del ejemplo anterior en PHP 7:


Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'baz',
)
Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'baz',
)

Salida del ejemplo anterior en PHP 5:


Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'bar',
)
Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'baz',
)

Notas

Nota:

Como esta función depende del ámbito actual para determinar los detalles del parámetro, no puede ser usada como parámetro de función en versiones anteriores a 5.3.0. Si se require pasar el valor, los resultados deben ser asignados a una variable y esta variable debería pasarse como parámetro.

Nota:

Si los argumentos se pasan por referencia, cualquier cambio en ellos se verá reflejado en los valores devueltos por esta función. A partir de PHP 7, los valores actuales también serán devueltos si los argumentos son pasados por valor.

Nota: Esta función solamente devuelve una copia de los argumentos pasados, y no rinde cuentas de los argumentos predeterminados (no pasados).

add a note add a note

User Contributed Notes 10 notes

up
50
T.M.
19 years ago
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
?>
up
17
anderson at francotecnologia dot com
15 years ago
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
?>
up
5
foxkeys at gmail dot com
8 years ago
Merge func_get_args() with function defaults
<?php
class utils {
 
/**
   * @param mixed[] $args
   * @param ReflectionMethod $reflectionMethod
   *
   * @return array
   */
 
public static function mergeArgsWithDefaults( $args, \ReflectionMethod $reflectionMethod ) {
    foreach (
array_slice( $reflectionMethod->getParameters(), count( $args ) ) as $param ) {
     
/**
       * @var ReflectionParameter $param
       */
     
$args[] = $param->getDefaultValue();
    }
    return
$args;
  }
}

class 
sampleParent {
  const
USER_FILE_TYPE_FILE = 'FILE';
  public function
select( $idUserFile = null, $idUserFileType = self::USER_FILE_TYPE_FILE ) {
    echo
'[$idUserFile=>' . $idUserFile . ', $idUserFileType=>' . $idUserFileType, ']<br/>' . PHP_EOL;
  }
}

class
sample extends sampleParent {
  const
USER_FILE_TYPE_IMG = 'IMG';
  public function
select( $idUserFile = null, $idUserFileType = self::USER_FILE_TYPE_IMG ) {
    return
call_user_func_array( 'parent::select', \utils::mergeArgsWithDefaults( func_get_args(), new ReflectionMethod( __CLASS__, __FUNCTION__ ) ) );
  }
}

$sample1 = new sampleParent();
$sample1->select();//Prints "" / self::USER_FILE_TYPE_FILE
$sample1->select(1);//Prints 1 / self::USER_FILE_TYPE_FILE
$sample1->select(2, 'test 1');//Prints 2 / "test 1"
echo '<br/>' . PHP_EOL;
$sample2 = new sample();
$sample2->select();//Prints "" / self::USER_FILE_TYPE_IMG
$sample2->select(3);//Prints 3 / self::USER_FILE_TYPE_IMG
$sample2->select(4, 'test 2');//Prints 4 / "test 2"
?>
up
3
mitko at edabg dot com
15 years ago
<?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>
*/

?>
up
1
Anonymous
22 years ago
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";
?>
up
3
OpenTechnologist
12 years ago
please note that optional parameters are not seen/passed by func_get_args(), as well as func_get_arg().

ex:

<?php
function testfunc($optional = 'this argument is optional..') {
   
$args = func_get_args();
   
var_dump($args);
    echo
$optional;
}
?>

test case #1:
testfunc('argument no longer optional..');

result for #1:
array(1) {
    [0]=>  string(20) "argument no longer optional.."
}
argument no longer optional..

test case #2:
testfunc('argument no longer optional..','this is an extra argument');

result for #2:
array(2) {
    [0]=>  string(29) "argument no longer optional.."
    [1]=>  string(25) "this is an extra argument"
}
argument no longer optional..

test case #3: -- RESULTS IN AN EMPTY ARRAY
testfunc();

result for #3:
array(0) {
}
this argument is optional..
up
2
cobrattila at gmail dot com
4 years ago
If you want to get the arguments by reference, instead of func_get_args() you can simply use

<?php
function args_byref(&...$args) {
   
// Modify the $args array here
}
?>

Credits should go to Markus Malkusch for pointing this out on Stackoverflow.
https://stackoverflow.com/a/29181826/1426064
up
0
ario [a] mail [dot] utexas [dot] edu
16 years ago
"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"
up
0
daveNO at ovumSPAMdesign dot com
22 years ago
<?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");
?>
up
-2
maarten at ba dot be
11 years ago
it seems that this function only returns a copy and loses it's byref information, use this dirty non-efficient workaround instead:

at the moment of writing it currently returns all of them as references, instead of only the ones who are passed that way...

<?php
function func_get_args_byref() {
       
$trace = debug_backtrace();
        return
$trace[1]['args'];
}
?>
To Top