Chapter 5. Expectations and Assertions
PHP has had an assert() function since PHP 4; it gives you the ability to add sanity-checks to your code. assert() is intended for development use only, and it can be easily enabled and disabled using assert_options() or the assert.active INI setting.
To use assertions, you pass in either an expression or a string as the first argument. If you pass in a string, it is evaluated by the assert() function as code. If the expression result, or the result of evaluating the string evaluates to false, then a warning is raised.
Example 5-1. Using assertions
assert('$user instanceof \MyProject\User');assert($userinstanceof\MyProject\User);
Single versus double quotes
Ensure that you use single quotes; otherwise, variables will be interpolated.
In Example 5-1, we see the same assertion using a string and an expression. If either of these evaluates to false, then a warning is raised:
Warning: assert(): Assertion "$user instanceof \MyProject\User" failed in <file> on line <num>
Using string assertions
While eval() is typically frowned upon, if you pass a string into assert() and assertions are disabled, the string is not evaluated at all. Using strings is considered best practice.
Expectations
With PHP 7, assert() has been expanded by the Expectations RFC, allowing for so-called zero-cost assertions.
With this change, you not only disable assertions, but you can also remove all overhead entirely. With this setting, assertions are not compiled, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access