Func get args php function

Func get args php function

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

func_get_args

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

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

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

Читайте также:  Элемент time в HTML

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 ;
>

$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.

See Also

User Contributed Notes 11 notes

Simple function to calculate average value using dynamic arguments:
function average () return array_sum ( func_get_args ())/ func_num_args ();
>
print average ( 10 , 15 , 20 , 25 ); // 17.5
?>

If you want to get the arguments by reference, instead of func_get_args() you can simply use

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

How to create a polymorphic/»overloaded» function

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:
// 😛
$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
?>

Merge func_get_args() with function defaults
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 , ‘]‘ . 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__ ) ) );
>
>

Читайте также:  Javascript работа с консолью

$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 ‘
‘ . 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»
?>

please note that optional parameters are not seen/passed by func_get_args(), as well as func_get_arg().

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..

// 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 ];
>

// 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 ;
>

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

/*
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.
*/

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 . «
\n» ;
$foo -> bar = «new bar» ;
echo «global_bar: » . $global_bar . «
\n» ;
/*
Result:
foo->bar: default bar

global_bar: bar global

*/

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

global_bar: new bar

*/

Читайте также:  Html css templates with slider

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.

function foo($bar=true) echo count(func_get_args());
>

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.

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

function foo ( $list )
echo implode ( ‘, ‘ , $list );
>

function foo2 ()
foo ( func_get_args ());
>

?>

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

function foo ( $list )
echo implode ( ‘, ‘ , $list );
>

function foo2 ()
foo ( $args = func_get_args ());
>

?>

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

Источник

func_get_args

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

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

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

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 ;
>

$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.

See Also

Источник

Оцените статью