Language basics
This chapter ....
Table of contents
Introduction
[TBA]
Constants
PHP provide ways to define constants: Either using
the const
keyword or the define()
function:
const FOO = 'foo'; define('FOO', 'foo');
The difference between those two ways is that const
defines constants at compile time, whereas define()
defines them at run time.
This means that some constructs that are illegal
with const
can be used with define()
. For
example, making the definition conditional is only legal
with define()
.
if (…) { const FOO = 'foo'; // ILLEGAL } else { define('FOO', 'foo'); // OK }If you try to assign a value to
const
that cannot be
assigned until runtime, you get a WSOD (but no error is logged).
const FOO = t('bar'); // WSOD define('FOO', t('bar')); // OK
Constant arrays using define()
was introduced in PHP
7.0 (older versions allowed this with const
, bit since
PHP 7.0, both can be arrays:
const FOO = [1, 2, 3]; define('FOO', [1, 2, 3]);
The keyword const
can be used within a class or interface
to define a class constant or interface
constant. The define()
function cannot be used for this
purpose:
class Foobar { const FOO = 'bar; // OK } class Foobar { define('FOO', 'bar'); // INVALID }
Recent changes to PHP
Backwards incompatible changes
count()
In PHP prior to 7.2, the
function count()
returned 0 if it was given an argument that was not countable (e.g. NULL, integer, string).
A new function is_countable()
was introduced in PHP 7.3, and you can do this to emulate the legacy behaviour.
/* * Helper function to emulate count() prior to PHP 7.2. */ private function _Count($arg) { return is_countable($arg) ? count($arg) : 0; }https://www.drupal.org/forum/support/module-development-and-code-questions/2021-03-11/help-figuring-out-undefined-function
New constructs in PHP 7
The short array syntax was introduced in PHP 5.4.
The spaceship (<=>
) operator comes from Perl, Ruby and Groovy. It offers a combined comparison:
0 if $a == $b -1 if $a < $b 1 if $a > $b
Source: wiki.php.net.
The null coalescing operator (??
) comes from C# and can be
used to avoid isset()
to check if a variable exists:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; // old way $username = $_GET['user'] ?? 'nobody'; // new way
PHP 7.x allows return type declarations, further enhanced in 7.1 by making them (and parameters) nullable. This is very much like C#, as is the types of return typing like this:
function arraysSum(array ...$arrays): array
Strict type enforcement (from PHP 7.1). Just put this line at the top of the page:
declare(strict_types=1);
Final word
[TBA]
Last update: 2021-03-11 [gh].