I know that in PHP when you want the function parameters to reference target variables we use the ampersand & sign. But I can not figure out if it is still valid and reliable in the following scenario (where variables are gathered from a request).
$v1 = $_POST['v1'];
function filled(&$var) {
return isset($var) && !empty($var);
}
if (!filled($v1)) // etc.
or even in this scenario:
$v1 = $_POST['v1'];
$v2 = $_POST['v2'];
function filled() {
$args = &func_get_args(); // does this even take the references and not the values?
foreach ($args as &$arg) {
if (empty($arg) || !isset($arg)) return false;
}
return true;
}
if (!filled($v1, $v2)) // etc.
Thanks in advance for clarification.
It is still valid since references don’t care if the variables are user defined or come from PHP superglobals, but there are a couple of issues with your first example.
First, when you do
$v1 = $_POST['v1'];$v1is now independent of the$_POST['v1']variable. Any changes to$v1are not reflected in$_POST['v1']because you made a copy.You could do:
$v1 = &$_POST['v1'];to create a reference to it.Second, your call to
issetin the function will always return true.issetis a special language construct, and not a function. If$_POST['v1']is unset,$v1will still be set (but will be null) after the assignment of$_POST['v1']to$v1.Also, as far as I know,
func_get_args()doesn’t support references, all the values it returns are copies of the original.Does that clear up some of your questions? If not, feel free to ask on anything you want clarified.