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. : 

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. 

Most popular PHP magic methods
PHP most popular magic methods

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.