Most Popular PHP Magic Methods
PHP features the concept of magic methods : methods that have a special function. They are related to other PHP features, and are automatically called on an object, when available.
For example, the __toString() method is called whenever an object is converted to a string : this may be with a type cast, a call to echo or print, or a concatenation. When such method is not available, a default behavior is used.
There are no less than 15 magic methods in PHP. :
- __construct
- __destruct
- __call
- __callStatic
- __get
- __set
- __isset
- __unset
- __sleep
- __wakeup
- __toString
- __invoke
- __set_state
- __clone
- __debugInfo
Most Popular PHP Magic Methods
We polled a corpus of 1705 Open Source applications, to check their respective usage of magic methods. Anytime a project defines, at least once, a magic method, it is counted.
A few notes
- All magic methods are quite popular. This is a widely used concept.
- The most common magic method is
__construct()
, by far. It is almost compulsory for a class, yet it is surprisingly low in usage, at 63%. __toString()
is quite popular__debugInfo()
was introduced in PHP 5.6__get()
is more popular than__set();
__sleep()is more popular than
__wakeup()`.__destruct()
is only used half the time of__construct()
.__serialize()
and__unserialize()
are only available in PHP 7.4. Either those projects are already compatible, or they will have to refactor some code.