declare

(PHP 4, PHP 5, PHP 7, PHP 8)

El constructor declare es usado para fijar directivas de ejecución para un bloque de código. La sintaxis de declare es similar a la sintaxis de otros constructores de control de flujo:

declare (directive)
    statement

La sección directive permite que el comportamiento de declare sea configurado. Actualmente, solamente están reconocidas tres directivas: ticks (véase abajo para más información sobre la directiva ticks), encoding (véase abajo para más información sobre la directiva encoding) y strict_types (para más infomación, véase la sección strict de la página de Argumentos de funciones)

Versión Descripción
7.0.0 Se añadió la directiva strict_types
5.3.0 Se añadió la directiva encoding

Ya que las directivas se manejan mientras el fichero está siendo compilado, solamente se pueden proporcionar literales como valores de directivas. No se pueden emplear variables ni constantes. Como ejemplo:

<?php
// Esto es válido:
declare(ticks=1);

// Esto no es válido:
const TICK_VALUE = 1;
declare(
ticks=TICK_VALUE);
?>

La parte statement del bloque declare será ejecutada - como se ejecuta y que efectos secundarios ocurran durante la ejecución puede depender de la directiva fijada en el bloque directive.

El constructor declare también se puede utilizar en el alcance global, afectando a todo el código que le sigue (sin embargo, si el archivo con el declare fue incluido entonces no afectará al archivo padre).

<?php
// estos son lo mismo:

// se puede usar ésto:
declare(ticks=1) {
// script entero aquí
}

// o se puede usar ésto:
declare(ticks=1);
// script entero aquí
?>

Ticks

Un tick es un evento que ocurre para cada sentencia tickable N de bajo nivel ejecutada por el intérprete dentro del bloque declare. El valor para N se especifica usando ticks=N dentro del bloque de declare de la sección directive.

No todas las sentencias son tickable. Por lo general, expresiones de condición y expresiones de argumento no son tickables.

Los eventos que ocurren en cada tick se especifican mediante la register_tick_function(). Ver el ejemplo abajo para más detalles. Tener en cuenta que más de un evento puede ocurrir por cada tick.

Ejemplo #1 Ejemplo de uso del tick

<?php

declare(ticks=1);

// Una función llamada en cada evento tick
function tick_handler()
{
echo
"tick_handler() llamado\n";
}

register_tick_function('tick_handler');

$a = 1;

if (
$a > 0) {
$a += 2;
print(
$a);
}

?>

Ejemplo #2 Ejemplo de uso de ticks

<?php

function tick_handler()
{
echo
"tick_handler() llamado\n";
}

$a = 1;
tick_handler();

if (
$a > 0) {
$a += 2;
tick_handler();
print(
$a);
tick_handler();
}
tick_handler();

?>

Véase también register_tick_function() y unregister_tick_function().

Encoding

Una codificación de script puede ser especificada para cada script usando la directiva encoding.

Ejemplo #3 Declarando un encoding para el script

<?php
declare(encoding='ISO-8859-1');
// código aquí
?>

Precaución

Cuando se combina con espacios de nombres, la única sintaxis legal para declarar es declare(encoding='...'); donde ... es el valor del encoding. declare(encoding='...') {} resultará en un error de análisis cuando se combina con espacios de nombres.

El valor declarado de encoding es ignorado en PHP 5.3 a menos que php esté compilado con --enable-zend-multibyte.

Tener en cuenta que PHP no expone si --enable-zend-multibyte fue utilizado para compilar PHP que no sea por phpinfo().

Ver también zend.script_encoding.

add a note add a note

User Contributed Notes 10 notes

up
61
Anonymous
14 years ago
It's amazing how many people didn't grasp the concept here. Note the wording in the documentation. It states that the tick handler is called every n native execution cycles. That means native instructions, not including system calls (i'm guessing). This can give you a very good idea if you need to optimize a particular part of your script, since you can measure quite effectively how many native instructions are in your actual code.

A good profiler would take that into account, and force you, the developer, to include calls to the profiler as you're entering and leaving every function. That way you'd be able to keep an eye on how many cycles it took each function to complete. Independent of time.

That is extremely powerful, and not to be underestimated. A good solution would allow aggregate stats, so the total time in a function would be counted, including inside called functions.
up
22
Kubo2
9 years ago
Note that in PHP 7 <?php declare(encoding='...'); ?> throws an E_WARNING if Zend Multibyte is turned off.
up
10
digitalaudiorock at gmail dot com
5 years ago
A few important things to note for anyone using this in conjunction with signal handlers:

If anyone is trying to optionally use either pcntl_async_signals() when available (PHP >= 7.1) or ticks for older versions, this is not possible...at least not in a way that does NOT enable ticks for newer PHP versions. This is because there is simply no way to conditionally declare ticks. For example, the following will "work" but not in the way you might expect:

<?php
if (function_exists('pcntl_async_signals')) {
   
pcntl_async_signals(true);
} else {
    declare(
ticks=1);
}
?>

While signal handlers will work with this for old and new version, ticks WILL be enabled even in the case where pcntl_async_signals exists, simply because the declare statement exists. So the above is functionally equivalent to:

<?php
if (function_exists('pcntl_async_signals')) pcntl_async_signals(true);
declare(
ticks=1);
?>

Another thing to be aware of is that the scoping of this declaration changed a bit from PHP 5.6 to 7.x...actually it was corrected apparently as noted here:

http://php.net/manual/en/function.register-tick-function.php#121204

This can cause some very confusing behavior. One example is with the pear/System_Daemon module. With PHP 5.6 that will work with a SIGTERM handler even if the script using it doesn't itself use declare(ticks=1), but does not work in PHP 7 unless the script itself has the declaration. Not only does the handler not get called, but the signal does nothing at all, and the script doesn't exit.

A side note regarding ticks that's annoyed me for some time: As if there wasn't enough confusion around all this, the Internet is full of false rumors that ticks were deprecated and are being removed, and I believe they all started here:

http://www.hackingwithphp.com/4/21/0/the-declare-function-and-ticks

Despite a very obscure author's note at the very end of the page saying he got that wrong (that even I just noticed), the first very prominent sentence of the article still says this, and that page is near the top of any Google search.
up
22
sawyerrken at gmail dot com
11 years ago
In the following example:

<?php
function handler(){
    print
"hello <br />";
}

register_tick_function("handler");

declare(
ticks = 1){
   
$b = 2;
}
//closing curly bracket tickable
?>

"Hello" will be displayed twice because the closing curly bracket is also tickable.

One may wonder why the opening curly bracket is not tickable if the closing is tickable. This is because the instruction for PHP to start ticking is given by the opening curly bracket so the ticking starts immediately after it.
up
5
digitalaudiorock at gmail dot com
5 years ago
Regarding my previous comment as to the change in scope of declare(ticks=1) between 5.6 and 7.x, I intended to mention another example of the affect this can have on signal handlers:

If your script uses declare(ticks=1) and assigns handlers, in 5.6 signals will get caught and call the handler even when the code that is running is in an included file (where the included file doesn't have the declaration). However in 7.x the signal wouldn't get caught until the code returns to the main script.

The best solution to that is to use pcntl_async_signals(true) when it's available, which will allow the signals to get caught regardless of what file the code happens to be in.
up
6
php dot net at e-z dot name
11 years ago
you can register multiple tick functions:

<?PHP
function a() { echo "a\n"; }
function
b() { echo "b\n"; }

register_tick_function('a');
register_tick_function('b');
register_tick_function('b');
register_tick_function('b');

?>

will output on every tick:
a
b
b
b
up
5
fok at nho dot com dot br
21 years ago
This is a very simple example using ticks to execute a external script to show rx/tx data from the server

<?php

function traf(){
 
passthru( './traf.sh' );
  echo
"<br />\n";
 
flush(); // keeps it flowing to the browser...
 
sleep( 1 );
}

register_tick_function( "traf" );

declare(
ticks=1 ){
  while(
true ){}   // to keep it running...
}

?>

contents of traf.sh:
# Shows TX/RX for eth0 over 1sec
#!/bin/bash

TX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`
sleep 1
TX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`

echo -e "TX: $[ $TX2 - $TX1 ] bytes/s \t RX: $[ $RX2 - $RX1 ] bytes/s"
#--= the end. =--
up
3
ja2016 at wir dot pl
7 years ago
Don't use uft-8 encoding with BOM. Then fatal error occurs ALWAYS. Substitute it with utf-8 without BOM.

---

*BOM*
<?php
declare(strict_types=1);
//Fatal error: strict_types declaration must be the very first statement in the script
up
4
markandrewslade at dontspamemeat dot gmail
15 years ago
Note that the two methods for calling declare are not identical.

Method 1:

<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list(
$sec, $usec) = explode(' ', microtime());
   
printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 1
declare(ticks=1);
while(
1) sleep(1);

/* Output:
[1234544435.7160] Tick.--start--
[1234544435.7161] Tick.
[1234544435.7162] Tick.
[1234544436.7163] Tick.
[1234544437.7166] Tick.
*/

?>

Method 2:
<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list(
$sec, $usec) = explode(' ', microtime());
   
printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 2
declare(ticks=1) {
    while(
1) sleep(1);
}

/* Output:
[1234544471.6486] Tick.--start--
[1234544472.6489] Tick.
[1234544473.6490] Tick.
[1234544474.6492] Tick.
[1234544475.6493] Tick.
*/
?>

Notice that when using {} after declare, do_tick wasn't auto-called until about 1 second after we entered the declare {} block.  However when not using the {}, do_tick was auto-called not once but twice immediately after calling declare();.

I'm assuming this is due to how PHP handles ticking internally.  That is, declare() without the {} seems to trigger more low-level instructions which in turn fires tick a few times (if ticks=1) in the act of declaring.
up
1
ohcc at 163 dot com
4 years ago
It's possible to set directives at one time if every directive is supported.
<?php
   
declare(strict_types=1, encoding='UTF-8');
?>
To Top