php get function arguments
func_get_args
func_get_args — Возвращает массив, содержащий аргументы функции
Описание
Получает массив, содержащий аргументы функции.
Эта функция может быть использована совместно с func_num_args() и func_get_arg() для создания функций с переменным количеством аргументов.
Возвращаемые значения
Возвращает массив, в котором каждый элемент является копией соответствующего члена списка аргументов пользовательской функции.
Ошибки
Генерирует предупреждение при вызове вне определения функции.
Примеры
Пример #1 Пример использования func_get_args()
Результат выполнения данного примера:
Пример #2 Использование func_get_args() до и после PHP 5.3
test.php
function foo () <
include ‘./fga.inc’ ;
>
Вывод в PHP 5.3 и выше:
Пример #3 Пример передачи аргументов по ссылке и по значению с func_get_args()
Результат выполнения данного примера в PHP 7:
Результат выполнения данного примера в PHP 5:
Примечания
Так как для определения параметров данной функции необходим контекст выполнения, она не может быть передана в качестве параметра в версиях PHP до 5.3.0. Если функцию все же необходимо передать, то нужно присвоить ее переменной, которую уже можно использовать при передаче.
Если аргументы были переданы по ссылке, то все изменения аргументов будут отражены на возвращаемых функцией значениях. В PHP 7 также будут возвращены текущие значения, если аргументы переданы по значению
Замечание: Эта функция возвращает только копии переданных аргументов, и не возвращает значения по умолчанию (непереданных) аргументов.
func_get_args — Возвращает массив, содержащий аргументы функции
Описание
Возвращает массив, содержащий аргументы функции.
Эта функция может быть использована совместно с func_num_args() и func_get_arg() для создания функций с переменным количеством аргументов.
Возвращаемые значения
Возвращает массив, в котором каждый элемент является копией соответствующего члена списка аргументов пользовательской функции.
Список изменений
Ошибки
Генерирует предупреждение при вызове вне определения функции.
Примеры
Пример #1 Пример использования func_get_args()
Результат выполнения данного примера:
Пример #2 Использование func_get_args() до и после PHP 5.3
test.php
function foo () <
include ‘./fga.inc’ ;
>
Вывод в PHP 5.3 и выше:
Пример #3 Пример передачи аргументов по ссылке и по значению с func_get_args()
Результат выполнения данного примера:
Примечания
Так как для определения параметров данной функции необходим контекст выполнения, она не может быть передана в качестве параметра в версиях PHP до 5.3.0. Если функцию все же необходимо передать, то нужно присвоить ее переменной, которую уже можно использовать при передаче.
Если аргументы были переданы по ссылке, то все изменения аргументов будут отражены на возвращаемых функцией значениях.
Замечание: Эта функция возвращает только копии переданных аргументов, и не возвращает значения по умолчанию (непереданных) аргументов.
func_get_arg
(PHP 4, PHP 5, PHP 7, PHP 8)
func_get_arg — Вернуть элемент из списка аргументов
Описание
Возвращает указанный аргумент из списка аргументов пользовательской функции.
Эта функция может быть использована совместно с func_get_args() и func_num_args() для создания функций с переменным количеством аргументов.
Список параметров
Номер аргумента. Аргументы функции считаются с нуля.
Возвращаемые значения
Возвращает указанный аргумент или false в случае возникновения ошибки.
Ошибки
Генерирует предупреждение при вызове вне определения функции, или если position больше реально переданного количества аргументов.
Примеры
Пример #1 Пример использования func_get_arg()
Результат выполнения данного примера:
Пример #2 Пример передачи аргументов по ссылке и по значению с func_get_arg()
Результат выполнения данного примера:
Примечания
Если аргументы были переданы по ссылке, то все изменения аргументов будут отражены на возвращаемых функцией значениях. В PHP 7 также будут возвращены текущие значения, если аргументы переданы по значению
Замечание: Эта функция возвращает только копии переданных аргументов, и не возвращает значения по умолчанию (непереданных) аргументов.
Смотрите также
User Contributed Notes 5 notes
This functions seems so powerful. just when i saw it i thought about writing a fast average of n numbers function so here it is, it is very simple. example usage included.
//Calculate the average of the numbers given
This function may work differently from php5 to php7, in the latter it seems to reference the variable, while in php5 it returns the original argument.
I have confirmed with the versions below, but this will require further confirmation as to whether this is a 5 versus 7 issue.
//in php 5.5.9, this script will write ‘321’
//in php 7.0.33, this script will write ‘123’
func_get_arg() returns a *copy* of the argument, to my knowledge there is no way to retrieve references to a variable number of arguments.
I have a module system in my game at http://lotgd.net where I’d like to be able to pass a variable number of arguments to functions in a module, and pass them by reference if the module asks for it by reference, but you can’t accept optional parameters as references, nor can you retrieve the reference on a variable number of arguments. Looks like my modules will have to do with out the ability to accept parameters to their functions by reference.
func_get_arg() does not appear to be allowed to be used as a function argument itself within class constructors in PHP 5.0.2 (wonk-ay. ):
class DEF extends ABC
<
function __construct ()
<
parent :: __construct ( func_get_arg ( 0 ),
func_get_arg ( 1 ),
func_get_arg ( 2 ));
>
>
?>
The above script generates:
Fatal error: func_get_arg(): Can’t be used as a function parameter in c:\Inetpub\wwwroot\phpwasrc\chapter10\xxx.php on line 23
There are, however, no problems when passing these as parameters to regular functions.
Php get function arguments
To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.
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».
*/
?>
A function’s argument that is an object, will have its properties modified by the function although you don’t need to pass it by reference.
In function calls, PHP clearly distinguishes between missing arguments and present but empty arguments. Thus:
The best approach, it seems to me, is to always use a sentinel like null as the default value of an optional argument. This way, callers like g and g’s clients have many options, and furthermore, callers always know how to omit arguments so they can omit one in the middle of the parameter list.
PASSING A «VARIABLE-LENGTH ARGUMENT LIST OF REFERENCES» TO A FUNCTION
As of PHP 5, Call-time pass-by-reference has been deprecated, this represents no problem in most cases, since instead of calling a function like this:
myfunction($arg1, &$arg2, &$arg3);
provided you have defined your function as
function myfuncion($a1, &$a2, &$a3) < // so &$a2 and &$a3 are
// declared to be refs.
.
>
In the following code I tried to amend this by using the
array() language-construct as the actual argument in the
call to the function.
func_get_args
(PHP 4, PHP 5, PHP 7, PHP 8)
func_get_args — Возвращает массив, содержащий аргументы функции
Описание
Получает массив, содержащий аргументы функции.
Эта функция может быть использована совместно с func_num_args() и func_get_arg() для создания функций с переменным количеством аргументов.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает массив, в котором каждый элемент является копией соответствующего члена списка аргументов пользовательской функции.
Ошибки
Генерирует предупреждение при вызове вне определения функции.
Примеры
Пример #1 Пример использования func_get_args()
Результат выполнения данного примера:
Пример #2 Пример передачи аргументов по ссылке и по значению с func_get_args()
Результат выполнения данного примера:
Примечания
Если аргументы были переданы по ссылке, то все изменения аргументов будут отражены на возвращаемых функцией значениях. В PHP 7 также будут возвращены текущие значения, если аргументы переданы по значению
Замечание: Эта функция возвращает только копии переданных аргументов, и не возвращает значения по умолчанию (непереданных) аргументов.
Смотрите также
User Contributed Notes 10 notes
If you want to get the arguments by reference, instead of func_get_args() you can simply use
How to create a polymorphic/»overloaded» function
/*
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.
*/
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.
please note that optional parameters are not seen/passed by func_get_args(), as well as func_get_arg().
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..
result for #3:
array(0) <
>
this argument is optional..
«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 foo2 ()
<
foo ( func_get_args ());
>
?>
However, you can easily get around this by doing the following:
?>
This captures the context from foo2(), making this legal. You get the expected output:
// How to simulate named parameters in PHP.
// By Dave Benjamin
// Do some magic.
extract ( varargs ( func_get_args ()));
// 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 ;
>
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.