php – What is the use of declaring variables using curly braces?

Question:

In PHP, variables usually have a pattern to be followed in their declaration.

According to the manual:

Variables in PHP are represented by a dollar sign ($) followed by the variable name. Variable names in PHP are case sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name begins with a letter or underscore, followed by any number of letters, digits, or underscores.

However, I noticed that it is possible to "escape" this rule, when defining the name of a variable.

Examples:

${1} = 1; // valor com número

${'1 variavel'} = 'número iniciando';

${'Nome com espaço'} = 'Wallace';

${'***Testando***'}[0][] = 'Array Louco';

Result:

Array
(
    [1] => 1
    [1 variavel] => número iniciando
    [Nome com espaço] => Wallace
    [***Testando***] => Array
        (
            [0] => Array
                (
                    [0] => Array Louco
                )

        )

)

In addition to variables being able to be declared like this, it is also possible (I think from PHP 5.4 onwards) to make the methods "escape" a little from their standard.

class Teste
{
    public function __call($method, $arguments)
    {
           echo "Método numérico [$method]";
    }

    public static function __callStatic($method, $arguments)
    {
        echo "Método númérico estático [$method]";
    }
}

Teste::{'10'}(); // Método numérico estático [10]

$teste = new Teste;

$teste->{'10'}(); // Método numérico 

After all, what's the point of variables being able to be declared in curly braces?


Is there any case that this is useful?

Answer:

Brackets are used in the declaration of variables when there is a need to use nomenclatures with reserved characters or characters that could cause a syntax error in a normal declaration.

It is also used to invoke variables in the assembly of object method names or simple functions.

Example:

/**
Declaração normal
*/
$foo = 'bar';

/**
Suponhamos uma situação onde queremos declarar o nome de uma variável contendo caracter de espaço. Fatalmente provocará erro.
*/
$foo bar = 'teste';

In this case, we can use the keys

${'foo bar'} = 'teste';

This is also called a variable variable : http://php.net/manual/en/language.variables.variable.php

In another situation, it is not allowed to declare variables with numeric names

$1 = 'val';
$2 = 'val';
$3 = 'val';

However, this is possible using the special syntax with curly braces:

${1} = 'val';

Despite being similar to variable variable , the method with braces cannot access a variable variable .

$v = 1;
$$v = 'ok';

echo $$v; // escreve 'ok'
echo ${'1'}; // provoca erro
echo ${1}; // provoca erro

However, the opposite is possible

${2} = 'ok';
echo ${2}; // escreve 'ok'

$v = 2;
echo $$v; // escreve 'ok'

"Bizarre" things become "possible":

${'\\'} = 'val';
echo ${'\\'};

${'  '} = 'val';
echo ${'  '};

${'🐉'} = 'val';
echo ${'🐉'};

${null} = 'val';
echo ${null};

${''} = 'val';
echo ${''};

${'Wallace gosta do michel teló.'} = 'val';
echo ${'Wallace gosta do michel teló.'};

/**
Nesse último exemplo, percebemos que o intuito não é permitir "coisas bizarras" para mero entretenimento. 
Podemos escrever códigos dessa forma:
*/
function foo()
{
    return null;
}

${foo()} = 'val';
echo ${foo()};

It gets a little more interesting when we try to use it in other places.

Invoking class methods dynamically:

class foo
{
    public static function bar()
    {
        return 123;
    }
}

echo foo::{'bar'}();

/**
Outras formas equivalentes:
*/
$m = 'bar';
echo foo::$m();

$o = 'foo';
$m = 'bar';
echo $o::$m();

$o = 'foo';
$m = 'bar';
echo ${'o'}::${'m'}();

Note that these features depend on the PHP version.
However, the programmer cannot travel in mayonnaise and abuse the resource.

injections
Care should also be taken with code injections from the user.

/**
O usuário pode tentar injetar códigos maliciosos
*/
$p = $_GET['eu_sou_burro_e_deixo_brecha_de_seguranca'];

${$p} = 'val';
echo ${$p};
Scroll to Top
AllEscort