What is the purpose of {} (keys) being used to delimit code in PHP?

4

In PHP, you can use the keys in any code snippet, for example, to separate blocks aesthetically.

Example:

{ $a = 1; }

{
    class X{}
}

{
    {
        function x() {}
    }
}

In these examples, none of them an error is generated.

I fully understand the importance of using parentheses in some cases. As in this example:

($a + $b) * $c;

$a + ($b * $c);

However, for keys, what is the purpose of PHP to allow this?

    
asked by anonymous 22.10.2015 / 21:19

1 answer

5

According to the PHP documentation

  

Any PHP script is built by a series of instructions. An   statement can be an assignment, a function call, a 'loop',   a conditional statement, or even an instruction that does nothing (a   command empty). Instructions usually end with a semicolon.   In addition, statements can be grouped into a group of commands   through the encapsulation of a group of commands with keys. A group   command is an instruction as well. The various types of instructions are   described in this chapter.

Although very badly written or translated, it means that you can group blocks of commands, for example when you use if or for , these instructions will execute the next command or command block.

// Executando o próximo comando.
if ($foo == $bar)
     echo 'comando a ser executado';

// Executando o próximo bloco de comando.
if ($foo == $bar) {
     echo 'inicio do bloco de comando';
     echo 'meio do bloco de comando';
     echo 'final do bloco de comando';
}

Another way to use keys is to use variables in the middle of strings that are double-quoted.

$str = "Uma string contendo a váriavel {$teste}";
$str = "Uma string apresentando um atributo {$this->teste}";
$str = "Uma string apresentando uma posição de um atributo {$this->teste[1]}";

Keys do not start a new code scope, they only group a group of commands.

Another very common application in C # known as regions is grouping codes for documentation, but honestly I think it only pollutes the code.

// Comentando o bloco seguinte de ações
{
    echo 'imprime alguma coisa';
    $a = 2;
    $b = 3;
    $c = 4;
    $x = $a + $b * $c;
    echo $x;
}

With the above code pooling, in some editors you can collapse the code by omitting it.

    
13.11.2015 / 17:39