Handling Changes in Magic Methods
Learn about the changes in magic methods introduced in PHP 8.
We'll cover the following
Now, let’s have a look at how inconsistencies in handling Exception
and exit
in the class constructor have been addressed in PHP 8.
Addressing inconsistencies in the class constructor
Another issue addressed in PHP 8 has to do with a situation where the class construct method either throws an Exception
or executes exit()
. In PHP versions prior to PHP 8, if an Exception
is thrown in the class constructor, the __destruct()
method, if defined, is not called. On the other hand, if either exit()
or die()
(both PHP functions are equivalent to each other) is used in the constructor, the __destruct()
method is called. In PHP 8, this inconsistency is addressed. Now, in either case, the __destruct()
method is not called.
You may be wondering why this is of concern. The reason why we need to be aware of this important change is that we might have logic residing in the __destruct()
method that was called in a situation where we also might call either exit()
or die()
. In PHP 8, we can no longer rely upon this code, which may cause a backwards-compatibility break.
In this example, we have two connection classes. ConnectPdo
uses the PDO extension to provide query results, whereas ConnectMysqli
uses the MySQLi extension:
We begin by defining an interface specifying a query method. This method requires an SQL string as an argument and is expected to return an array as a result:
Get hands-on with 1400+ tech skills courses.