What is the use of declaring variables through braces?

Asked

Viewed 855 times

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. Variable names in PHP distinguish between upper and lower case.

Variable names follow the same rules as other labels in 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" from 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';

Upshot:

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 declared like this, it is also possible (think from PHP 5.4), to make methods "run away" a little of your pattern.

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 variables being declared between braces ?


Is there any case that would be helpful?

  • 1

    I think there was a similar question about declaring variables, including some close examples. I’ll see if I think.

  • 1
  • @rray, this one. I looked for a long time and did not find... :) I remember it was very enlightening when I read.

  • 1

    @Papacharlie, there’s this other one too Is there a problem using Unicode characters for code identifiers?.

  • The issue at hand is "why php accepts this and whether I can use it"

  • 1

    When questions are weird and at the level of curiosities are usually asked by @Wallacemaxters rsrsrsr, deserves the +1 for the dedication in seeking "curiosities"

Show 1 more comment

2 answers

6


Brackets are used in the variable declaration when there is a need to use placeholder names or characters that could cause 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 that case, we can use the keys

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

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

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

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

However, this is possible using special key syntax:

${1} = 'val';

Although it is similar to variable variable, the key method 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()};

The thing gets a little more interesting when we try to use in other places.

Calling 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 such 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};
  • -1. I don’t like Michel Teló. A lie I gave -1. I gave +1. But I don’t like Michel Teló, really!

  • His reply was satisfactory ;)

3

Are keys. Brackets = (), Brackets = [] and keys = {}.

It is not only to declare, it is to reference variables, which includes declaring.

This use you found I did not know the closest was the 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 for values.

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

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

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

Only it has an unwanted space, rewriting:

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

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

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

So it will work properly.

Another case is explained in the PHP documentation

To be able to use variable variables with arrays, you need solve an ambiguity problem. So, if you write $$a[1] then the interpreter can understand that you want to use $a[1] as a variable or that you want to use $$a 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.

Anyway, your observation may not be documented.

When it comes to unexpected behavior, there is a comment that speaks of the use of variable with the name this when not passed directly: http://php.net/manual/en/language.variables.basics.php#107080

Sources: http://php.net/manual/en/language.variables.basics.php http://php.net/manual/en/language.variables.variable.php http://php.net/manual/en/reserved.variables.globals.php

  • It does not clarify the question much. That keys are used to print the variables, avoiding collision between the name the variable and a string is normal. But what about the statement? It is recommended to declare variables with "exotic names"?

  • 1

    Ah, and +1 for the precious information of $this.

  • Sempe I forget the difference between brackets and keys

Browser other questions tagged

You are not signed in. Login or sign up in order to post.