What is the Declare keyword in PHP for?

Asked

Viewed 683 times

14

After all, what is the key word for declare in PHP?

I’ve seen explanations around, including in Manual for PHP, but still I did not find its functionality very clear.

It can be useful for development?

Example:

declare (ticks=1) {
    // todo script aqui
}
  • 4

    I read the documentation and I was left with even more doubts.

  • He doesn’t "declare" anything, does he? Too weird!

  • And then there’s that register_tick_function to complete further the confusion!

  • 2

    It seems that this feature will be discontinued in PHP 7. But it would still be nice to know what it’s about, in addition to knowing the motivation behind Feature. :)

  • from what I understand, you use the declare to define how many ticks you will use, and then use the ticks to call the function... or something like that

  • I don’t know if it’s @Rodrigoborth, because ticks=1 executes 1, but ticks=2 doesn’t work

  • I was really wrong, after reading a lot and doing the tests I came to an answer

Show 2 more comments

2 answers

16


Well, in the PHP manual we have

The declare statement is used to define execution directives for a code block.

Below is the following sentence

The Directive section allows the behavior of the declare block to be defined. Currently two 'Directive' are recognized: the 'Directive' ticks (...) and the 'Directive' encoding (...)

That in the case does not explain anything

All below that are explanations of how each of the directive work.

From the explanation and the tests it’s very confusing to know why we use the directive ticks but from what I understand you use the declare(ticks=N) to define how many functions you need to use for it to print what you have registered. Example:

function tick_handler(){
   echo "tick_handler() called <br>";
}
//crieu uma função para registrar em um tick

register_tick_function('tick_handler');
//registrei a função no tick

$a = 10;
//atribui um valor para a variavel

declare(ticks=1){
   if ($a > 0) {
       $a += 2;
       print($a.'<br>');
   }
}

The above example will bring the following result:

tick_handler() called  //desaparece caso apague a linha 14
12                     //desaparece caso apague a linha 15
tick_handler() called  //desaparece caso apague a linha 15
tick_handler() called  //desaparece junto dos anterios caso apague o if
tick_handler() called  //sempre são exibidos
tick_handler() called 

In what way the directive ticks intrfere in the code above?
Simple, the value of ticks defines how many ciclos nativos(chamadas do sistema não contam) need to be executed so that the register_tick_function be executed.

That is why for each erased line of code the number of responses is reduced. and increasing the value assigned to ticks increases the number of cycles needed for it to execute the call of the registered function.

NOTE: If you bring line 9 within the scope of the declare you will have one more run of the register_tick_function

OBS2: If you do a while infinite and empty it will run the register_tick_function every cycle.

What use is that?
If you are using a native function and have no idea how it is executed by PHP you can use the ticks to know how many cycles they took to execute.

Worth it?
I believe not, we can use microtime to know how long the server takes to process anything without an overload, because running a function each N cycles will be increasing the time to have a response, leaving it with a failure, as you can see, the 2 cycles being displayed even without any function being called within the scope of the declare and we don’t have an accuracy of how many cycles it’s actually taking to perform our function

NOTE Each statement that PHP executes (save a few exceptions) is a "native cycle" Thanks @bfavaretto

NOTE² Ticks will be removed in PHP 6.
Source: Tuxradar

NOTE³ PHP 6 will no longer be released and it is currently not possible to tell if the Ticks will be present in PHP 7


And as for the declare(encoding='...')?
There isn’t much to talk about. The only thing he does is define the encoding page. You can’t use it to define a encoding different for a certain part of the code (I would be very happy if I could) because when you try to do this occurs the following error:
"Encoding declaration pragma must be the very first statement in the script"

OTHER NOTE According to a comment in the php manual it overwrites the zend.script_encoding set in php.ini

I found that question in the gringo SO on the encoding statement unanswered yet.

  • 5

    Each statement that PHP runs (save a few exceptions) is a "native cycle". I think this example, derived from your, a little clearer: the Handler is called 4 times (one for each increment, and another for the line of the }).

  • I read somewhere that the declare(ticks) will be removed from the language or at least will be obsolete. Does anyone confirm? It would be interesting then to talk about the declare(encoding) which seems more relevant to me?

  • @bigown also read this somewhere, I’ll just be sure about the encoding and already complement the answer

  • Note. PHP6 will no longer be released. I don’t know if this will be valid for PHP7

  • Rodrigo and @bigown has not been removed in php7, on the contrary a new directive has been added strict_types: http://php.net/manual/en/control-structures.declare.php

5

In PHP 7 another directive has been added: strict_types. This one I see is quite useful in development because it "undoes" a part of the "mess" of types that PHP has, leaving the developer a little more in control of the application than before.

Considering the function:

function increment(int $x): int
{
    return $x + 1;
}

echo increment('1'); // 2

See working on Repl.it | Ideone

Naturally PHP tries to do the cast of the input value for the type that is expected; that is, if called increment('1'), PHP would treat the string as whole and return 2 as if nothing had happened.

When using the declare(strict_types=1), you inform the interpreter that you want to work in the restricted form of types, in which PHP will no longer do Casts magic. The same example above, with the strict_types would be:

declare(strict_types=1);

function increment(int $x): int
{
    return $x + 1;
}

echo increment('1');

See working on Repl.it | Ideone

In this case, a fatal error would be given:

PHP Fatal error: Uncaught Typeerror: Argument 1 passed to increment() must be of the type integer, string Given, called in ...

The same works for the return type of the function which, if defined, must be followed or otherwise will return a fatal error.

Browser other questions tagged

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