July 27, 2008 by Christoff Truter PHP
I wanted to write a blog about func_get_arg(s) for quite a while now. Since its
a very handy function in PHP, but never got around doing it.
Until I ran into an interesting issue last week, while working on a new article
for my website.
Lets have a look at the function before continuing, so that everyone knows what
I am talking about. What we've got here is functionality which allows developers
to pass parameters to a function, without needing to literally define them.
function demonstrate()
{
$num_args = func_num_args();
for ($i = 0; $i < $num_args; $i++)
{
echo func_get_arg($i);
}
}
demonstrate("a","b","c"); // outputs abc
function increment($a)
{
$a++;
}
$value = 10;
increment(&$value);
echo $value."<br/>"; // Value correctly echoed as 11
function increment2()
{
$a = func_get_arg(0);
$a++;
}
increment2(&$value);
echo $value."<br/>"; // Value still 11
$value = 11;
function increment3()
{
$a = func_get_arg(0);
$a->scalar++;
}
$value = (object)$value; // Similar to Boxing
increment3($value);
$value = $value->scalar; // Essentially our unboxing
echo $value."<br/>"; // Value correctly echoed as 12
<?php
$a = 11;
function increment4()
{
$a = func_get_arg(0);
$a++;
return array($a);
}
list($a) = increment4($a);
echo $a; // Value correctly echoed as 12
?>
$value = 11;
function increment5()
{
$stack = debug_backtrace();
$stack[0]["args"][0]++;
}
increment5(&$value);
echo $value."<br/>"; // Value correctly echoed as 12
January 2, 2014 by Darth Killer
Found this page during a search, and i'd like to mention something i found during said research : the debug_backtrace() approach was depreciated, and since PHP 5.4.0 no longer allowed at all. :/ http://stackoverflow.com/questions/7026872/how-to-pass-unlimited-arguments-by-reference-in-php/7035378#7035378 Meanwhile, i think i'll bookmark your blog for later exploring. ;)