How to update legacy constructor methods in PHP 7

When I was fiddling with my P2 Categories theme last week, debug mode generated several warnings when run in PHP 7.2.1. That’s because class methods are no longer allowed to have the same name as the class itself.

This was allowed in PHP 5 and earlier, but from what I gather it’s no longer the way to do things. Back then such methods were used as constructors, or in other words, methods that would be run automatically when the class is instantiated.

Let’s take an example from the P2 theme. Here’s the beginning of the P2 class as of version 1.5.8:

class P2 {
	// ...
	function P2() {
            // ...

This will work just fine in PHP 5, but will generate a warning in PHP 7 (even though the code will execute). To update this, all we need to do is change our function name to __construct (notice the two underscores at the beginning of the name):

class P2 {
	// ...
	function __construct() {
            // ...

Anything inside the __construct() function is executed as soon as an instance of the class is created.

When updating legacy code, there is the risk that the previous function name is called during instantiation. Consider this:

class P2_Post_List_Creator extends P2_List_Creator {
	var $form_action_name = 'p2-post-task-list';

	function P2_Post_List_Creator() {
		parent::P2_List_Creator();
                // ...

Here a class extends another class and calls a constructor method of the parent class by name. If we had just patched the parent class with _construct(), the child class would throw an “undefined function” error.

To avoid this we’ll also have to update any calls made to the original constructor method, like so:

class P2_Post_List_Creator extends P2_List_Creator {
	var $form_action_name = 'p2-post-task-list';

	function P2_Post_List_Creator() {
		parent::__construct();
                // ...

And that’s really all there’s to it.





You can leave a comment on my original post.