Recently, I discovered that Datetime::createFromImmutable is now returning a
static type : it returns an object of the type that called the method. This is only useful when the class has been extended by another class.
This means that the
Datetime class is extended enough for PHP to acknowledge it and adapts its features.
Extending PHP native classes is possible, though I rarely used it in my own code : initially, it sounded odd. Then, of course, I remembered the Exception class, and all its derivative. So, it is actually common.
The question became : “Which of PHP classes are extended?”. So, I turned to my faithful Static Code Analyzer Exakat, and ran some stats. Here are the raw numbers, and a quick context and analysis after that.
- RuntimeException : 1715
- Exception : 1564
- InvalidargumentException : 1185
- LogicException : 340
- FilterIterator : 188
- UnexpectedvalueException : 173
- Error : 128
- stdClass : 117
- BadmethodcallException : 116
- ArrayIterator : 115
- Arrayobject : 99
- Splfileinfo : 93
- Datetime : 64
- Datetimeimmutable : 62
- DomainException : 48
- OutofboundsException : 45
- Pdo : 31
- SessionHandler : 26
- IteratorIterator : 24
- RecursiveDirectoryIterator : 22
- ErrorException : 21
- Datetimezone : 21
- Dateinterval : 21
- Reflectiontype : 21
- PdoException : 19
- Splstack : 16
- Reflectionparameter : 15
- Reflectionclass : 14
- Reflectionmethod : 13
- Splqueue : 13
- Splpriorityqueue : 13
- RecursivefilterIterator : 13
- php_user_filter : 12
- Reflectionfunction : 11
- Exceptions are ranking high in that list. Surprisingly,
RuntimeExceptionis ahead of the pack, even before
Exception. That is good.
- The other exceptions are less extended, and it should be higher. May be more training and blog posts are needed?
- Iterators, ArrayObjects and Spl are ranking quite high : just like Exceptions, they are meant to be extended. Although, there is again a short list of actually extended iterators.
stdClasscomes as a surprise : until PHP 8.2, there is no real need to extend it. After PHP 8.2, I expect these number to grow, as it is a way to have dynamic properties.
- Pdo is quite intriguing, including PdoException. How does that work? PdoException is caught, then thrown again with an new type? Native PHP won’t through anything but PdoException, so there is some custom adapation.
The list of extended classes is build by analysis 2887 PHP open source projects, and extracting all PHP native classes that are extended with the
extends keyword. Deeper extension where not considered, they are very rare by nature, and not statistically significant.
Classes extensions with more than 10 cases are listed here. 10 is an arbitrary limit.