PHP tips
A pot-pourri of 8 PHP tips that were published with @exakat account.
strict_types exceptions
strict_types do not apply to #PHP operators, only on to typed structures.
Here, concatenation and interpolation all call __toString(), but not foo().
As you can see, print() and echo() are safe too, while implode() is not.
__invoke() and properties and methods
What does this tricky #PHP code displays?
Tweet
Method syntax and __invoke()
There are some other cases around instanceof, which are surprising upon first read.
We can use a string in a variable, but not a direct string, a constant nor a ::class.
Tweet
object is not a type
Such situations always make me smile, yet I am certain several of us will loose time on such a mistake.
Tweet
PHP keywords and namespaces
I was today’s old when I realized that #PHP keyword are allowed in namespaces name since #PHP 8.0.
This goes to PHP 8.0 Compatibility ruleset.
Tweet
PHP silent optimisation
PHP optimisation in action : undefined variables are only reported when they are used.
first is omitted : no operation
second is skipped : no need to execute 2nd term
third is reporting a warning.
PHP recycles
TIL PHP recycles the previously created stdClass objects. The following code returns Object #1, until it is stored in $b.
TIL (2) : PHP’s stdClass’s constructor omits all its arguments.
When integer overflows
Mathematics have the ‘Ramanujan Summation’, where the sum of all integers is -1/12.
#PHP has the integer overflow. Stay away from the PHP_INT_MAX limits. Valid with (int) or intval() with recent #PHP versions.