Jasper
Jasper

Reputation: 2404

A variable references bug?

I have a cannot understand problem, the following code why is print Array ( [a] => 1 [b] => 2 [c] => 3 [d] => ) , I didn't change the $info variable but why it changed?

<?php
function ifSetOr(&$a, $b = null) {
    return isset($a) ? $a : $b;
}

$info = array('a' => 1, 'b' => 2, 'c' => 3);
ifSetOr($info['d']);
print_r($info); //Array ( [a] => 1 [b] => 2 [c] => 3 [d] => ) 
?>

Upvotes: 0

Views: 46

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24576

You implicitly created $info['d'] when you passed it as a reference.

For this reason a ifSetOr function like that can never work. You cannot pass around nonexisting variables. Also keep in mind that "parameters" for isset are an exception because isset is not really a function but a language construct.

Upvotes: 3

Related Questions