4

I know you can pass a variable number of arguments to a function an access them individually.

For example

function foo()
{
    $arg = func_get_arg(0);
    $arg += 10;
}

$a = 100;

foo($a);

echo "A is $a\n";

But those arguments are passed by value as demonstrated above.

Is it possible to use them as if they was passed by reference in a similar manner to functions like bind_param in the mysqli library?

2
  • perhaps php.net/manual/en/function.func-get-arg.php, example #3, can help you Commented Mar 10, 2013 at 11:48
  • @Amir Example 3 does not help with variable number of arguments because you usually omit these arguments from the method signature, so you cannot signify them with &. Commented Mar 10, 2013 at 12:42

2 Answers 2

1

First thing I want to mention: Don't use references.

That aside: Doing that directly is impossible as the engine has to know whether something is a reference before calling the function. What you can do is passing an array of references:

$a = 1; $b = 2; $c = 3;
$parameters = array(&$a, &$b, &$c, /*...*/);
func($parameters);

function func(array $params) {
    $params[0]++;
}
Sign up to request clarification or add additional context in comments.

4 Comments

There is nothing wrong with references if you know what you are doing (and I would to implement a function that can modify multiple arguments upon completion). Any enough of the plug for your web site.
Well in 99% of the cases there are better designs than using references. For instance using object-oriented designs. An object-oriented design can be cleaner, more maintainable and, especially with PHP 5.4, be faster and require less memory.
Where does the 99% come from?
Obviously not a scientific number, but a conclusin after almost 15 years of using PHP and about 10 years of working on the engine itself.
1

You cant, simply you cant tell the php that this is by reference and that is not, But! I recommend doing the following :

function foo()
{
    $arg = func_get_arg(0);
    $arg->val += 10;
}
$a =new stdClass();
$a->val = 100;
foo($a);
echo "$a\n"; // 110 

you can apply boxing to the value you want and it works, Hope you find this helpful, if you have any questions please ask.

1 Comment

@Nathaniel: Do not make edits that add substantial amounts of extra information. Do so in a comment or in a new answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.