Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP declare Statement
The PHP declare statement allows you to control the execution environment of a script block. Its syntax is similar to other control structures like while, for, and foreach loops.
Syntax
declare (directive) {
statement1;
statement2;
// ...
}
The behavior of the block is defined by the type of directive. Three types of directives can be used: ticks, encoding, and strict_types.
Ticks Directive
A tick is a special event that occurs after a certain number of tickable statements are executed. You can register a function to run on tick events using register_tick_function().
Example
This example executes myfunction() every 5 ticks ?
<?php
function myfunction() {
echo "Hello World<br>";
}
register_tick_function("myfunction");
declare (ticks=5) {
for ($i = 1; $i <= 10; $i++) {
echo $i . "<br>";
}
}
?>
1 2 3 4 5 Hello World 6 7 8 9 10 Hello World
PHP also provides unregister_tick_function() to remove the association of a function with tick events.
Strict Types Directive
PHP normally performs automatic type coercion. The strict_types=1 directive prevents this behavior, enforcing strict type checking.
Without Strict Types
<?php
function myfunction(int $x, int $y) {
return $x + $y;
}
echo "total=" . myfunction(1.99, 2.99);
?>
total=3
With Strict Types
<?php
declare (strict_types=1);
function myfunction(int $x, int $y) {
return $x + $y;
}
echo "total=" . myfunction(1.99, 2.99);
?>
Fatal error: Uncaught TypeError: Argument 1 passed to myfunction() must be of the type integer, float given
Encoding Directive
The encoding directive specifies the character encoding scheme for the script ?
<?php declare(encoding='ISO-8859-1'); echo "This Script uses ISO-8859-1 encoding scheme"; ?>
Conclusion
The declare statement provides fine-grained control over script execution. Use strict_types for type safety, ticks for performance monitoring, and encoding for character set specification.
