'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 ?

php


Solution 1:[1]

From the documentation:

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

To me this implies that if you use ${...}, there are no limitations regarding what characters may be used in a variable name. Whether you should however...

Solution 2:[2]

PHP parser provides a special syntax to create a variable name from any expression that returns string (or can be casted to string), eg.:

<?php

define('A', 'aaa');

${'    _   '} = 'blah';
${'test' . A . (2 + 6)} = 'var';

echo ${'    _   '}; // blah
echo ${'testaaa8'}; // var

${'123'} = 'blah';
echo ${100 + 23}; // blah

function returnVarName() {
    return 'myVar';
}

$myVar = 12;
echo ${returnVarName()}; // 12

This syntax is also available for object properties:

$object->{' some property    ... with strage name'};

0x0 is just a hex representation of 0 literal.

Solution 3:[3]

In other words everything within the curly braces in such cases is a string!

So s0x0 is indeed the hex version of 0 but here both are strings! That is why ${0x0} or ${0} work, where $0 or $0x0 won't!

Solution 4:[4]

On top of what @Michael Robinson said, in your example this will also be valid:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Robinson
Solution 2 Crozin
Solution 3 Grijesh Chauhan
Solution 4 Marko D