PHP 8 elephant plushy

PHP 8: Idiosyncrasies, Oddities, Obscurities and Updates (Part 1)


I originally intended to write this in three parts (beginner, intermediate and advanced). However, my notes are more extensive than I realised that they would be, so that's not going to happen. There will be substantially more than three parts, so as not to make each of them seriously lengthy.

As I pointed out in the previous post that introduced the idea, this is not meant to teach PHP 8 to complete beginners. (I assume that you are already familiar with an earlier version of it.) It's not exactly meant to be a cheat-sheet, either. Rather, it falls somewhere between the two, consisting of both the things that are new to the language and those which I never learned or forgot since last I used it. (Some of these things are likely to already be known to you.) Here, then, is the first part of an extensive list:

Miscellaneous

  • Despite what advocates of other/newer languages might proclaim, PHP is not dead or languishing on old servers. It's certainly not in danger of that happening, either. Over 75% of Websites where the technologies in use are known use PHP.
  • The echo statement is slightly more efficient than the print ($var) function, when it comes to outputting simple strings.

Constants, Datatypes and Variables

  • By default, variable assignment and passing is done by value. To do so by reference, use an ampersand (&) beforer the dollar sign: $x = &$y;
  • PHP supports string interpolation without the use of braces:
    print ("My name is $name."); /* can also be "My name is {$name}." or "My name is ${name}." */
  • String interpolation doesn't work in strings that use single quotes.
  • There are two ways to define constants:
    1. define ("NAME", value); // case-sensitive, defined at run-time, can be dynamic: define ("STATUS_". $paid, $paid);
    2. const NAME = value; // defined at compile time
  • When used, constants don't have a dollar sign in front of them: print (STATUS_PAID);
  • To determine if a constant has been defined, use the defined("CONSTANT") function.
  • PHP supports variable variables:
    $foo = "bar"; $$foo = "baz"; print ("{$foo}, ${$foo}, {$bar}"); // bar, baz, baz
  • To find the datatype of a variable, use the gettype ($var) or var_dump ($var) function(s). The difference between them is that the former will return a string, whereas the latter prints it.
  • PHP arrays/lists can simultaneously contain values of mixed datatypes.
  • To view the contents of an array, use the print_r ($arr) function. For the sake of readability, place it within <pre> tags.
  • In functions, it's possible to specify the types of arguments (instead of relying on PHP to infer them):
    function xy (int x, int y) { /* ... */ } /* This only guarantees the type on entry into the function; they are still subject to conversion in the body */
  • It is possible to enable strict/strong typing mode, which will throw type mismatch errors for mismatching types, even if an implicit conversion/cast could be performed. To do this, use declare (strict_types = 1); at the top of a PHP file. Using this is recommended for improved code quality and reducing bugs.
  • Strict mode does have an exception to the rule: integers can be converted to floats without throwing type mismatch errors.
  • In addition to Heredoc, PHP 8 introduces Nowdoc. The main difference is that heredoc treats a string as if it is enclosed in double quotes (and supports string interpolation), whereas Nowdoc treats it as if it's enclosed in single quotes (and doesn't support string interpolation).
  • To preserve new lines in HTML when outputting Heredoc and/or Nowdoc, use the nl2br ($string) function.
  • The syntax for declaring Nowdoc is similar to Heredoc, except that the terminator must be enclosed in single quotes:
    $string = <<<'TERM'
    Here's some Nowdoc text!
    TERM;
  • In PHP, null is a case-insensitive constant. However, since case-insensitive constants are deprecated and discouraged in PHP 8, one should use the convention that constants are in uppercase.
  • null is loosely equivalent to zero (0), an empty array and an empty string (''), which is why print (null) results in blank output. However, It is not equivalent to false, which is loosely equivalent to zero. Go figure ...
  • Unlike with strings, arrays cannot use negative indices for elements.
  • To get the length of an array, use the count ($arr) function, not len ($arr).
  • The array_push ($arr, value, ...) function can push multiple values onto the end of an array.
  • It is not possible to have duplicate keys within an array; the last one will overwrite the others. Keys also have to be integers or strings, although PHP will convert them to integers if it can. (Booleans, floats and nulls do not work as array keys.)
  • If one defines an array key that is not sequential to the previous ones, the next one will be one more than that:
    $arr = [1, 2, 5 => 3, 4]; print_r ($arr); // (0 => 1, 1 => 2, 5 => 3, 6 => 4)
  • Using the array_shift ($arr) function will remove the first element of an array will remove the first element of an array, but it will also re-index the array. On the other hand, unset ($arr[$index]) does not re-index the array.
  • The difference between isset ($arr[$index]) and array_key_exists($arr[$key]) is that the former checks if the key both exists and is not null, whereas the latter only checks the key exists. (The difference is not just a difference in casing convention used).

Operands and Operators

"Hello, operator,
Will you give me number nine?
Will I see you later?
Will you give me back my dime?"
 — Jack White/The White Stripes; Hello Operator

  • The "spaceship" comparison operator (<=>) is a combination of less-than (<), equal to (==) and greater-than (>). It behaves in a similar way to  Java's .compareTo (T x, T y) method. The logic is this:
    if ($x < $y) return -1; elseif ($x == $y) return 0; else return 1;
  • Before PHP 8, comparing an int or float to a non-numeric string would convert the string to zero (0) and perform numeric comparison. In PHP 8, the number is instead converted to a string before comparison. This can potentially introduce bugs in existing code. To illustrate:
    $result = (0 == "I have become death, the destroyer of worlds!");
    /* PHP_VERSION <8: (0 == 0) => true; PHP_VERSION >= 8: ("0" == "I have become death ...") => false */
  • Only numeric strings get converted to numbers in PHP 8 comparisons: (6 == '9') => (6 == 9)
  • The null-coalescing operator (??) is used when working with variables that either are null or could be null. (This is useful in the case that a variable is undefined. An undefined variable evaluates to null.) For example:
    $x = 1; $y = $x ?? "X is null"; // if (is_null ($x)) $y = "X is null"; else $y = $x;
  • The @ operator supresses errors. It is strongly advised that you don't use it, because it does not allow for graceful error handling.
  • The increment (++) operator, when applied to a string, will increase the value of the last character therein: "abc"++ => "abd"

To be continued in subsequent parts ...


Thumbnail image copyright Site Ground

How do you rate this article?

4


Great White Snark
Great White Snark

I'm currently seeking fixed employment as a S/W & Web developer (C# & ASP .NET MVC, PHP 8+, Python 3), hoping to stash the farmed fiat and go full Crypto, quit the 07:30-18:00 grind. Unsigned music producer; snarky; white; balding; smashes Patriarchy.


Return to the Source
Return to the Source

Use the Force; read the source! This blog is mostly a collection of study notes on ASM, ASP .NET, Blender, BASIC, C/C++, C#, ChucK, Computer Architecture, Computer Literacy, CSS, Digital Logic, Electronics, F#, GIMP, GTK+, Haskel, Java, Julia, JavaScript (ES6+) & JSON, LISP, Nim, OOP, Photoshop, PLAD, Python, Qt, Ruby, Scheme, SQL (MySQL & SQLite), Super Collider, UML, Verilog, VHDL, WASM, XML. If I can learn it and make notes on it, I'll write about it. || Blog images copyright Markus Spiske and Pixabay

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.