I have a small function to get element values from an array/object:
<?php
function element( $ind, &$var, $def = NULL ) {
echo "inside: ".json_encode(isset($var) ? $var : '<unset>') . PHP_EOL;
if (isset($var) && is_array($var)) {
return empty($var[$ind]) ? $def : $var[$ind];
}
if (isset($var) && is_object($var)) {
return empty($var->{$ind}) ? $def : $var->{$ind};
}
return $def;
}
echo "var before: ".json_encode(isset($myvar) ? $myvar : '<unset>') . PHP_EOL;
$value = element( 'zz', $myvar, '' );
echo "var after: ".json_encode(isset($myvar) ? $myvar : '<unset>') . PHP_EOL;
echo PHP_EOL;
echo "array before: ".json_encode(isset($myarray) ? $myarray : '<unset>') . PHP_EOL;
$value = element( 'zz', $myarray['yy'], '' );
echo "array after: ".json_encode(isset($myarray) ? $myarray : '<unset>') . PHP_EOL;
echo PHP_EOL;
echo "object before: ".json_encode(isset($myobject) ? $myobject : '<unset>') . PHP_EOL;
$value = element( 'zz', $myobject['yy'], '' );
echo "object after: ".json_encode(isset($myobject) ? $myobject : '<unset>') . PHP_EOL;
My problem is that if the $var passed is an array or an object but is not actually set, then it gets magically created, causing problems down the road:
$ php z.php
var before: "<unset>"
inside: "<unset>"
var after: "<unset>"
array before: "<unset>"
inside: "<unset>"
array after: {"yy":null}
object before: "<unset>"
inside: "<unset>"
object after: {"yy":null}
Any idea why this happens and how to prevent it?
EDIT
Ok I am getting a lot of "don't do that" and "tell somebody else to do something", so I will explain a bit more of the situation. I have a code base of over 300,000 lines of PHP code, which has been using the element() function to get values from all kinds of variables for years (called in more than 800 places) and now all of the sudden there crops up some issues due to the function magically creating variables that are not present. Specific case in point, there is a very large multi-dimensional array $member which was being passed as such:
<?php echo json_encode(element('base_name', $member[$wizard_type], ''); ?>
It is not clear what elements $member[xxx] will have in any given situation, and apparently in some situations it is not set, in which case it would be fine to just use empty string (3rd parameter.) Unfortunately this call actually sets $member[$wizard_type], and then later on code gets executed due to this which should not be.
If I could remove the reference and suppress the errors somehow from within the element() function that would be ok I suppose.