Variable with no name: $ {''}

So, variable variables exist. This means it works

$a = 'test';
$$a = 'Hello';
echo ${'test'}; //outputs 'Hello'

      

But now I came across some pretty weird code using a variable with no name:

function test(&$numRows) {
    $numRows = 5;
    echo ' -- done test';
}

$value = 0;
test($value);
echo ' -- result is '.$value;

test(${''}); //variable without name

      

http://ideone.com/gTvayV Code Script

Output:

- done test - result 5 - test performed

This means the code does not crash.

Now my question is, what exactly happens if the value $numRows

changes when the parameter is an unnamed variable? Will meaning be written into nirvana? Is this PHP variable equivalent /dev/null

? I haven't been able to find anything specific about this.

Thank you in advance

+3


source to share


2 answers


Now my question is, what exactly happens if the value of $ numRows is changed when the parameter is an unnamed variable?

There is no such thing as a variable without a name, an empty string in PHP is a fully valid name.

I may be wrong, but in PHP all variables are accessible by their names (more precisely, the string representation of their name), and since an empty string is still a string, it is considered a valid name.

Think of variables like an array key-value pair. You can create an array key with an empty string:

$arr = [];
$arr[''] = 'appul';
var_dump($arr['']); // prints: string(5) "appul"
$arr[''] = 'ponka';
var_dump($arr['']); // prints: string(5) "ponka"

      



Whenever you refer to $arr['']

, you are addressing the same value.

You can access all variables as a string using the $ GLOBAL variable, so you can check what's going on with your "unnamed" variable:

${''} = 'ponka';
var_dump($GLOBALS['']); // prints: string(5) "ponka"
${''} = 'appul';
var_dump($GLOBALS['']); // prints: string(5) "appul"

      

Will the meaning be written into nirvana? Is this PHP variable equivalent to / dev / null? I haven't been able to find anything specific about this.

No, it doesn't go to nirvana, it sits quietly in the global space, and it's a little harder to access it, but anyway, it's a normal variable like any other.

+1


source


${''}

is a valid variable whose name is an empty string. If you've never installed it before, it's undefined.

var_dump(isset(${''}));   // if you have never set it before, it is undefined.

      

You don't see any errors because you disabled the NOTICE error message.



error_reporting(E_ALL);
ini_set('display_errors', 1);

echo ${''}; // Notice: Undefined variable:

      

You can install it like this:

${''} = 10;
echo ${''};  // shows 10

      

+2


source







All Articles