declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
    statement

The directive section allows the behavior of the declare block to be set. Currently only one directive is recognized: the ticks directive. (See below for more information on the ticks directive)

The statement part of the declare block will be executed -- how it is executed and what side effects occur during execution may depend on the directive set in the directive block.

The declare construct can also be used in the global scope, affecting all code following it.

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    
// entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>

Ticks

A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Пример #1 Profile a section of PHP code

<?php
// A function that records the time when it is called
function profile($dump FALSE)
{
    static 
$profile;

    
// Return the times stored in profile, then erase it
    
if ($dump) {
        
$temp $profile;
        unset(
$profile);
        return 
$temp;
    }

    
$profile[] = microtime();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
    for (
$x 1$x 50; ++$x) {
        echo 
similar_text(md5($x), md5($x*$x)), "<br />;";
    }
}

// Display the data stored in the profiler
print_r(profile(TRUE));
?>
The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed. This information can then be used to find the slow areas within particular segments of code. This process can be performed using other methods: using ticks is more convenient and easier to implement.

Ticks are well suited for debugging, implementing simple multitasking, background I/O and many other tasks.

See also register_tick_function() and unregister_tick_function().

Коментарии

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);
}

register_tick_function"traf" );

declare( 
ticks=){
  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. =--
2003-07-07 21:45:59
http://php5.kiev.ua/manual/ru/control-structures.declare.html
The scope of the declare() call if used without a block is a little unpredictable, in my experience. It appears that if placed in a method or function, it may not apply to the calls that ensue, like the following:

<?php
function a()
{
   declare(
ticks=2);
   
b();
}

function 
b()
{
   
// The declare may not apply here, sometimes.
}
?>

So, if all of a sudden the signals are getting ignored, check this. At the risk of losing the ability to make a mathematical science out of placing a number of activities at varying durations of ticks like many people have chosen to do, I've found it simple to just put this at the top of the code, and just make it global.
2006-05-30 03:06:16
http://php5.kiev.ua/manual/ru/control-structures.declare.html
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(
1sleep(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(
1sleep(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.
2009-02-13 11:06:02
http://php5.kiev.ua/manual/ru/control-structures.declare.html
Автор:
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.
2010-09-27 17:10:48
http://php5.kiev.ua/manual/ru/control-structures.declare.html
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.
2013-08-09 09:31:37
http://php5.kiev.ua/manual/ru/control-structures.declare.html
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
2013-10-17 09:34:42
http://php5.kiev.ua/manual/ru/control-structures.declare.html
Basically 'declare( encoding = .... );' overrides the zend.script_encoding configuration option (as set in php.ini). However, keep in mind that:

* the file encoding must be compatible (at least in the ASCII range of characters) to the zend.script_encoding setting. If you set 'zend.script_encoding' to UTF-8 and save the file in UTF-16, PHP will not be able to interpret the file, let alone the declare statement. As long as you use ASCII compatible encodings (i.e. ISO-8859-1(5), UTF-8 etc) for both the file encoding as the zend.script_encoding, you should be fine. (However, I have not experimented with adding non-ascii characters in comments above the declare statement).

* PHP string literals are converted from your source code encoding (either set with the declare statement or else according to zend.script_encoding) to the mbstring.internal_encoding as set in your php.ini (even if you change the setting using mb_internal_encoding). As an example:

php.ini:
mbstring.internal_encoding = UTF-8

test.php:
<?php
declare(encoding 'ISO-8859-15');
mb_internal_encoding'ISO-8859-15' );
echo 
'aäaß' "\n";
?>

This will still output the string UTF-8 encoded; in a terminal/browser with encoding 'ISO-8859-15' the string will look (something) like this: aÀaß
2014-02-18 18:17:54
http://php5.kiev.ua/manual/ru/control-structures.declare.html
Автор:
Note that in PHP 7 <?php declare(encoding='...'); ?> throws an E_WARNING if Zend Multibyte is turned off.
2015-04-06 20:13:56
http://php5.kiev.ua/manual/ru/control-structures.declare.html
Автор:
I haven't found this written in the doc: when using declare in the global context, it has to be the first statement in the script, before any other output.

This works:

<?php
declare(strict_types=1);
function 
sum(int $aint $b): int {
    return 
5.78;
}
# ... but fails when calling the function
?>

This doesn't work:

<html>
<body>
<?php
declare(strict_types=1);
function 
sum(int $aint $b): int {
    return 
5.78;
}
# PHP Fatal error:  strict_types declaration must be the very first statement in the script [...]
?>
2017-02-10 08:36:53
http://php5.kiev.ua/manual/ru/control-structures.declare.html
If you fork'ed (with pcntl_fork) after you've used `declare`, you need to do it again in child thread.

declare(ticks=1);
$pid = pcntl_fork();
if ($pid === 0) {
    declare(ticks=1);
} else {
    // code ..
}
2017-08-01 11:49:11
http://php5.kiev.ua/manual/ru/control-structures.declare.html
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
2017-08-27 07:38:17
http://php5.kiev.ua/manual/ru/control-structures.declare.html
Using a directive that is not supported by current version of PHP will generate a warning like:

Warning: Unsupported declare 'strict_types' in D:\Server\wuxiancheng.cn\index.php on line 2

You CAN'T prepend an @ sign to the declare construct to supress that error message.

@declare(strict_types=1);

The above code will lead to a Parse error like:

Parse error: syntax error, unexpected 'declare' (T_DECLARE) in D:\Server\wuxiancheng.cn\index.php on line 2
2018-05-27 05:54:00
http://php5.kiev.ua/manual/ru/control-structures.declare.html

    Поддержать сайт на родительском проекте КГБ