Ian Hazzard
Ian Hazzard

Reputation: 7771

Variable Variables - errors and validity

I've been studying PHP for a little while now, and I ran across variable manipulation functionality officially called Variable Variables. The basic syntax is:

$foo = 'bar';
$$foo = 'foo2';

The result of these two statements is $foo equals bar, and a new variable, $bar equals foo2.

I expect that if variable $foo contained a number, this would throw some sort of error. What happens if the value of $foo is originally set to an invalid variable name? What error will be thrown?

Upvotes: 0

Views: 37

Answers (2)

James Westman
James Westman

Reputation: 2690

You can try it with this simple script:

<?php
    $foo='1';
    $$foo='hello world';
    echo $$foo;
?>

and this one:

<?php
    $foo='1';
    $$foo='hello world';
    echo $1;
?>

Basically, no error will be thrown if you do this. However, you must access the new variable as $$foo, not as $1. If you run both scripts, the first one will say "hello world" and the second will give an error in the log file.

EDIT: Thanks @Fabrício Matté for saying that you can access it like this:

<?php
    $foo='1';
    $$foo='hello world';
    echo ${1};
?>

Upvotes: 1

Tryth
Tryth

Reputation: 421

No error will be thrown.

The PHP Docs on Variables states that variables must match the following regex:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

However this rule is only enforced by the parser. PHP supports variables named anything, the parser just enforces certain naming conventions.

You can check it yourself:

$foo = '1';
$$foo = 'baz';
print_r(get_defined_vars());
/*
Prints:
Array
(
 ...
 [foo] => 1
 [1] => baz
)
*/

Upvotes: 2

Related Questions