What is the use of declaring variables using braces?

7

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

According to the manual:

  

Variables in PHP are represented by a dollar sign ($) followed by   variable name. The variable names in PHP distinguish between   uppercase and lowercase letters.

     

Variable names follow the same rules as other labels in the   PHP. A valid variable name starts with a letter or underline,   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 the variables being declared so, it is also possible (I think from PHP 5.4) to make the methods "run away" a little bit from their default.

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 is the purpose of the variables being declared between braces?   

  Is there any case that this is useful?
    
asked by anonymous 31.07.2015 / 20:48

2 answers

6

Variable declaration brackets are used when there is a need to use reserved character nomenclatures or characters that could cause syntax errors 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 : link

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 keys:

${1} = 'val';

Although it is similar to variable variable , the method with keys can not 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 ${'  '};

${'                                    
30.11.2015 / 09:17
3

They are keys. Parentheses = (), Brackets = [] and braces = {}.

It's not just for declaring, it's for referencing variables, which includes declaring.

This usage you found I did not know the closest was the variable variable name (see link below). It may also have something to do with the superglobal $GLOBALS , which is an indexed array and therefore accepts strings as keys to the values.

Anyway, answering the two questions: The purpose is to tell the interpreter or compiler or whatever you want, exactly which characters are part of the variable name. With the keys you can solve ambiguities.

Example: In PHP it is possible to write the name of the variables directly inside strings:

$inicio = "abc";
echo  "As primeiras seis letras são: $inicio def";

It just has an unwanted space, rewriting:

echo  "As primeiras seis letras são: $iniciodef";

Now the code will be interpreted incorrectly, expecting the variable $iniciodef which, at first, does not exist.

echo  "As primeiras seis letras são: ${inicio}def";

This will work correctly.

Another case is explained in the PHP documentation

  

In order to be able to use variable variables with arrays, you need   solving a problem of ambiguity. So, if you write $$ to [1]   then the interpreter might understand that you want to use $ a [1] as a   variable or you want to use $$ as a variable and [1] as the   index of this variable. The syntax for solving this ambiguity is   $ {$ a [1]} for the first case and $ {$ a} [1] for the second case.

In any case, your observation may not be documented.

In the case of unexpected behavior, there is a comment that talks about the use of variable with name this when not passed directly: link

Sources: link link link

    
31.07.2015 / 22:17