Using assertions in PHP

When writing code a lot of assumptions are done and must be done to make code easy to read and write.
Assertions can only be used for debugging purposes and should be turned off in production code. So no validation must rely on a assertion.

$x = 5;
assert($x > 10);

Running this code with assertions active will output the following because the expression $x > 10 will not yield true.

$ php -d assert.active=1 index.php 
PHP Warning:  assert(): Assertion failed in /home/leon/assert/index.php on line 5
PHP Stack trace:
PHP   1. {main}() /home/leon/assert/index.php:0
PHP   2. assert() /home/leon/assert/index.php:5

It is tempting to use assertions to validate parameters and to prevent invalid data to enter a system. The problem will come up when the assertions are turned off, then the whole validation is not working anymore.

class Person {
    private $age;
    
    public function setAge($age) {
        assert($age != 0);
        assert($age < 150);
        
        $this->age = $age;
    }
}

A better solution in this case would be to use a if statement that checks the arguments and throws an exception when some invalid value is entered.

class Person {
    private $age;

    public function setAge($age) {
        if ($age == 0 || $age > 150) throw new InvalidArgumentException("Invalid age");
        
        $this->age = $age;
    }
}

A real use case for assertions would be to check if an object exists when in normal circumstances this should not be a problem. During developing it can help to check those things.

class KeywordCollection {
    private $connector;
    
    public function save($document) {
        assert($this->connector instanceof MongoCollection);
        
        $this->connector->insert($collection, $document);
    }
}