PHP Keywords: declare and enddeclare

5 March 2019 - 9:03pm

Welcome to my series on every PHP keyword and its usage. Today's items: declare and enddeclare.

This keyword is used to declare certain properties for a specific block of code. The block can be delimited by curly braces {} or the enddeclare keyword. It can also be declared standalone, and will apply to all following code in the file, as well as any included files.

There are currently three different properties that can be declared using the declare construct:

Ticks

This is the number of "tickable" statements that will be fun before a function, registered through register_tick_function(), will run.

Tickable statements seem to consist of statements that are standalone, and not part of a conditional statement or an argument.

This declaration is mostly useful for analysing your own code, so I don't expect you to be using it very often.

<?php
register_tick_function(function()
{
    echo "Statement ran";
});

declare(ticks = 1)
{
    // The function will be run after every tickable statement within these braces
}

declare(ticks = 1);
    // The function will be run after every tickable statement between these statements
enddeclare;

declare(ticks = 1);
// The function will be run after every tickable statement until the end of this file

Encoding

This block declares the default encoding to use for strings throughout this block. By default, PHP will use the zend.script_encoding value declared in php.ini.

<?php
declare(encoding = "UTF-8")
{
    $string = "This is a utf-8 string";
}

declare(encoding = "UTF-8");
    $string = "This is a utf-8 string";
enddeclare;

declare(encoding = "UTF-8");
$string = "This is a utf-8 string";

Strict

Normally, PHP will automatically convert compatible types back and forth to match type hints. So an integer might be cast to a string, if passed to a function expecting a string. With strict mode turned on, PHP will consider the argument to be incorrect and throw a TypeError. This also applies to return types, so returning an integer when a string is expected will also throw a TypeError

<?php
function acceptString(string $x)
{
    return $x;
}

declare(strict_types = 1)
{
    // Throws a TypeError
    acceptString(1);
}

declare(strict_types = 1);
    // Throws a TypeError
    acceptString(1);
enddeclare;

declare(strict_types = 1);
// Throws a TypeError
acceptString(1);