Skip to content
Advertisement

Why is ${0x0} correct?

The following code is working perfectly:

${0x0} = 'test';
echo ${0x0}; // prints "test"

But I can’t figure out why. 0x0 (or 0, as non-hex people call it) is a random container, it could have been any number, but php variables can’t start with a number. What’s so special about the { } used here, and what are their limitations ?

Advertisement

Answer

First of all, 0x0 is just a regular 0 in hexadecimal representation that gets cast to string '0' when used with the variable variable syntax:

var_dump(0x0===0); // prints "bool(true)"

${0x0} = 'test';
echo ${0x0}; // prints "test"
echo ${'0'}; // prints "test" as well
var_dump(get_defined_vars()); // contains ["0"] => string(4) "test"

You’re correct whey you say that it isn’t a valid variable name:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ‘[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*’

This is the reason why $0foo = 'Test'; triggers a parse error.

Some quick testing with the variable variables syntax reveals that, in fact, PHP does not seem to really care about variable names as far as they are strings:

${'123 abc xyz    '} = 'Test';
echo ${'123 abc xyz    '}; // Test
echo ${'123 abc xyz   '}; // PHP Notice:  Undefined variable: 123 abc xyz    in ...
var_dump(get_defined_vars()); // ["123 abc xyz    "] => string(4) "Test"

My guess is that the aforementioned naming restriction is imposed by the source code parser rather than the language core. It needs such rules to tell variables apart when analysing PHP code. Internally, the Zend engine that powers PHP handles variables as a hash map:

PHP variables, in general, consist out of two things: The label, which might, for instance, be an entry in a symbol table, and the actual variable container.

So as far as it receives a valid string for the label, it’s happy.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement