|
|
 |
func_get_args (PHP 4, PHP 5) func_get_args --
Devuelve una matriz que comprende la lista de argumentos de una
función
Descripciónarray func_get_args ( void )
Devuelve una matriz en la cual cada elemento es una copia del
miembro correspondiente de la lista de argumentos de la
función definida por el usuario
actual. func_get_args() generará una
advertencia si es llamada desde afuera de una definición
de función. Esta función no puede ser usada
directamente como un parámetro de función. En su
lugar, su resultado puede ser asignado a una variable, la cual
puede ser pasada a la función.
Nota:
Esta función devuelve una copia de los argumentos pasados
únicamente, y no toma en cuenta las argumentas
predeterminados (no pasados).
Nota: 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.
Es posible usar func_get_args() en conjunto
con func_num_args() y
func_get_arg() para permitir que funciones
definidas por el usuario acepten listas de argumentos de longitud
variable.
bew
31-Mar-2006 07: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));
}
foo('a', 'b');
?>
Nathan Ostgard
06-Dec-2005 10: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-Feb-2005 12:47
# 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.
04-Nov-2004 07: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); ?>
volte6 at drunkduck dot com
30-Sep-2004 02:54
For those who have a use for a C style enum() function:
//*******************************************
// 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
23-Mar-2003 11:13
You can also fake named arguments using eval:
function test()
{ foreach (func_get_args() as $k=>$arg) eval ("\$$arg;");
echo "$a plus $b gives ".($a+$b);
}
test("a=3","b=4");
fbeyer at clickhand dot de dot noSpamPlease
19-Jan-2002 08:02
Another way of passing references with a dynamic number of arguments: (This example is limited to 10 arguments)
<?php
define('NULL_ARG', 'DUMMY_ARGUMENT');
function refArg($arg0 = NULL_ARG,
$arg1 = NULL_ARG,
$arg2 = NULL_ARG,
$arg3 = NULL_ARG,
$arg4 = NULL_ARG,
$arg5 = NULL_ARG,
$arg6 = NULL_ARG,
$arg7 = NULL_ARG,
$arg8 = NULL_ARG,
$arg9 = NULL_ARG)
{
for ($args=array(), $i=0; $i < 10; $i++) {
$name = 'arg' . $i;
if ($i < func_num_args()) {
$args[$i] = &$$name;
}
unset($$name, $name);
}
$args[0] = 'Modified.';
}
$test = 'Not modified.<br>';
refArg(&$test);
echo $test; ?>
daveNO at ovumSPAMdesign dot com
17-Sep-2001 11:29
<?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");
?>
04-Jun-2001 07: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.
<?
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";
?>
| |
| | Citas célebres | Las guerras seguirán mientras el color de la piel siga siendo más importante que el de los ojos. Bob Marley Músico jamaicano (1945-1981) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Tiendas | | Las utilidades del teflón | LLega un minero al almacén del pueblo, se acerca al dependiente y le dice:
- Deme unos calzoncillo con teflón...
- ¿Disculpe caballero? ¿Unos que?
- Unos calzoncillos con teflón, hombre. ¿Que no hablo claro, o está usted sordo?
- Debe estar usted confundido señor,el teflón es un recubrimiento que tienen los sartenes para que no se peguen los huevos.
- Pues precisamente, para eso los quiero. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|