How to determine if a pass-by-reference variable is set?

php

Solution

It's my understanding that you wish to implement a function that implements something like `preg_match`, whereby the third argument gets populated with the memory patterns if passed.

Internally, PHP functions use a function called `zend_parse_parameters()`; it accepts a format string and a variable number of arguments that will be populated with the meta data of the call parameters. If a parameter is not passed (e.g. when it's optional), the meta data is not available and thus is easy to detect.

Coming back to PHP itself, unfortunately there's no such thing as `func_arg_used($var)` that will tell you if `$var` was passed as a function argument; perhaps this would be an interesting contribution to the language, but until then you'll have to settle for something more ancient :)

if (func_num_args() > 1) {
    // $second was passed and can be used to populate
}

You may have to be careful when changing the signature of the function, especially when you add parameters in front of `$second`; however, naturally this shouldn't happen often because it would most definitely break dependent functions. Adding more arguments at the end has no effect on above code.

There are two ways you can go with this:

`ReflectionFunction` - the shiny new toy of developers, it allows you to introspect your function and determine whether the signature changed from when it was created. Use it sparingly though, introspection is not cheap, especially considering the alternativey.

The humble code comment - the much understated form of code policing; a simple line that says `// IMPORTANT - don't add arguments before $second`

Problem

For an arbitrary function declared as follows: ``` function foo($first, &$second = null) { // if ($second is assigned) { // Work with $second // } } ``` How does one determine if `$second` is indeed assigned to a variable at call time, eg.: ``` foo('hello', $second); ``` vs ``` foo('hello'); // Notice &$second is unassigned ``` Tried `isset()`, `is_null()` but they don't seem to work. Update: Created a test script here here

Original source