A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.php.net/manual/en/function.func-get-args.php below:

PHP: func_get_args - Manual

func_get_args

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

func_get_argsReturns an array comprising a function's argument list

Description

This function may be used in conjunction with func_get_arg() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Parameters

This function has no parameters.

Return Values

Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list.

Errors/Exceptions

Generates a warning if called from outside of a user-defined function.

Examples

Example #1 func_get_args() example

<?php
function foo()
{
$numargs = func_num_args();
echo
"Number of arguments: $numargs \n";
if (
$numargs >= 2) {
echo
"Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for (
$i = 0; $i < $numargs; $i++) {
echo
"Argument $i is: " . $arg_list[$i] . "\n";
}
}
foo(1, 2, 3);
?>

The above example will output:

Number of arguments: 3 
Second argument is: 2
Argument 0 is: 1
Argument 1 is: 2
Argument 2 is: 3

Example #2 func_get_args() example of byref and byval arguments

<?php
function byVal($arg) {
echo
'As passed : ', var_export(func_get_args()), PHP_EOL;
$arg = 'baz';
echo
'After change : ', var_export(func_get_args()), PHP_EOL;
}

function

byRef(&$arg) {
echo
'As passed : ', var_export(func_get_args()), PHP_EOL;
$arg = 'baz';
echo
'After change : ', var_export(func_get_args()), PHP_EOL;
}
$arg = 'bar';
byVal($arg);
byRef($arg);
?>

The above example will output:


As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

Notes

Note:

As of PHP 8.0.0, the func_*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter.

Note:

If the arguments are passed by reference, any changes to the arguments will be reflected in the values returned by this function. As of PHP 7 the current values will also be returned if the arguments are passed by value.

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

T.M.

20 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); ?>

anderson at francotecnologia dot com

16 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':
$sql = "id = {$args[0]}";
break;
case
'string':
$sql = "name LIKE '%{$args[0]}%'";
break;
case
'string|integer':
$sql = "name LIKE '%{$args[0]}%' AND status = {$args[1]}";
break;
case
'string|integer|integer':
$sql = "name LIKE '%{$args[0]}%' LIMIT {$args[1]},{$args[2]}";
break;
default:
$sql = '1 = 2';
}
return
mysql_query('SELECT * FROM table WHERE ' . $sql);
}
$res = select(29); $res = select('Anderson'); $res = select('Anderson', 1); $res = select('Anderson', 0, 5); ?>

daveNO at ovumSPAMdesign dot com

23 years ago

<?php
function varargs($args) {
$count = count($args);
for (
$i = 0; $i < $count; $i += 2) {
$result[$args[$i]] = $args[$i + 1];
}

return

$result;
}
function test(&$ref1, &$ref2) {
$foo = "oof"; extract(varargs(func_get_args()));

echo

nl2br("\n\$var1 = $var1");
echo
nl2br("\n\$var2 = $var2");
echo
nl2br("\n\$foo = $foo\n\n"); $ref1 = 42;
$ref2 = 84;
}
$a = 5;
$b = 6;

echo

nl2br("Before calling test(): \$a = $a\n");
echo
nl2br("Before calling test(): \$b = $b\n"); 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");
?>
foxkeys at gmail dot com

9 years ago

Merge func_get_args() with function defaults
<?php
class utils {
public static function mergeArgsWithDefaults( $args, \ReflectionMethod $reflectionMethod ) {
foreach (
array_slice( $reflectionMethod->getParameters(), count( $args ) ) as $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();$sample1->select(1);$sample1->select(2, 'test 1');echo '<br/>' . PHP_EOL;
$sample2 = new sample();
$sample2->select();$sample2->select(3);$sample2->select(4, 'test 2');?>
OpenTechnologist

13 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..
hans at loltek dot net

1 year ago

I wanted an associative list of arguments, in case some else does too, I'm leaving it here.

I hope PHP gets native support for this, because a core implementation would be faster than this userland backtrace+reflection implementation:


<?phpfunction func_get_args_associative(bool $populateMissingArgumentsWithDefaults = false): array
{
$trace = debug_backtrace(0, 2)[1];
$reflection = null;
if (isset(
$trace['class'])) {
$reflection = new \ReflectionMethod($trace['class'], $trace['function']);
} else {
$reflection = new \ReflectionFunction($trace['function']);
}
$ret = [];
foreach (
$reflection->getParameters() as $param) {
if (
array_key_exists($param->getPosition(), $trace['args'])) {
$ret[$param->name] = $trace['args'][$param->getPosition()];
} elseif (
$populateMissingArgumentsWithDefaults) {
assert($param->isDefaultValueAvailable(), "i think all params are either in trace[args] or have default values");
$ret[$param->name] = $param->getDefaultValue();
}
}
return
$ret;
}
?>
art at geigel dot com

2 years ago

The size of the array resulting from func_get_args(), for instance using count(), does not take into account parameters that have been assigned default values in the function definition.

Example:

function foo($bar=true) {


echo count(func_get_args());
}

foo();


// echoes 0

foo("bar");


// echoes 1

A useful condition to test for when a function needs to return default behavior (whatever that might be) when no value is present and the value of $bar could be true, false, null, etc.

info at ensostudio dot ru

17 days ago

Note: this function returns current values of variables instead passed to function

<?php
function test(int $v) {
$v = 2;
var_export(func_get_args());
}
test(1); ?>

maarten at ba dot be

12 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'];
}
?>

mitko at edabg dot com

16 years ago

<?php
class foo {

var

$bar = "default bar";

function

foo() {
$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";
$foo = & new foo(&$global_bar);
echo
"foo->bar: ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo
"global_bar: ".$global_bar."</br>\n";
?>
ario [a] mail [dot] utexas [dot] edu

18 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:

<?phpfunction 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:

<?phpfunction 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"

Anonymous

23 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
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";
?>


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.3