Sunday 21 September 2014

PHP: a fractal of [etc]... yeah, I'm now getting where you're coming from

G'day:
Null.


CFML has had a spotted history with the concept of null, and this has been very embarrassing and bloody inconvenient to boot. Fortunately it's finally getting there though (more in Railo than ColdFusion).

But today I had the misfortune of having a run-in with null in PHP.

This code demonstrates:

<?php
// test.php

$tests = [
    "null == 0",
    "null >= 0",
    "null <= 0",
    "null > 0",
    "null < 0",
    "null == 1",
    "null == -1",
    "null == true",
    "null == false",
    "null === false"
];

foreach ($tests as $test) {
    echo "$test<br>";
    $statement = "\$result = $test;";
    eval($statement);
    if ($result){
        echo "You're having a laugh, PHP<br>";
    }else{
        echo "Not so. Well that's a relief<br>";
    }
    echo "<hr>";
}

Output:

null == 0
You're having a laugh, PHP


null >= 0
You're having a laugh, PHP


null <= 0
You're having a laugh, PHP


null > 0
Not so. Well that's a relief

null < 0
Not so. Well that's a relief

null == 1
Not so. Well that's a relief

null == -1
Not so. Well that's a relief

null == true
Not so. Well that's a relief

null == false
You're having a laugh, PHP

null === false
Not so. Well that's a relief



What the actual f***?

OK - for reasons that should have resulted in the developer(s) involved being given a dose of projectio in profluentem - PHP considers null to be false, but... it just seems so wrong that null == 0 and null == false. I suppose it's just a fundamental flaw in the language: null is supposed to mean nothing other than "it's not anything", so prescribing that to mean "but it will also mean boolean false" is even worse than CFML's decision to reflect null as ""; at least CFML doesn't make concessions beyond that ("" is neither true not false, because it's a bloody string). I always thought that was the worst treatment of null I had seen. No. PHP is even worse.

Oh... the fractal thing, if you didn't know, is this: "PHP: a fractal of bad design".

--
Adam