How to write PHP 7 compatible codes

You might not be ready yet to refactor entire codebase to take advantage all the PHP 7 features, but at least make the current code you are writing compatible with PHP 7!

Posted by Darwin Biler on December 31, 2015

PHP 7 was just released. But this doesn't means all hosting provider will quickly jump into putting PHP 7 in all of your legacy sites. Imagine the horror if suddenly you have to refactor your 10-year old legacy site while you are in the middle of developing another project.

If you are currently developing some PHP site though, what you can do right now is to be aware of how to write PHP 7 compliant codes. So that you wont have to refactor it later when the time comes that your organization is ready for PHP 7. Here is some tips on how to make a PHP 7 compatible codes:

Don't use Alternative PHP Tags

Things like

<script language="php"> 
// Code here
</script>
and
<%  %>
<%=$varToEcho; %>

Don't use POSIX-Compatible Regular Expressions

The entire ext/ereg is removed. Avoid using these functions in your new projects

  • ereg()
  • eregi()
  • ereg_replace()
  • eregi_replace()
  • split()
  • spliti()
  • sql_regcase()

Don't use the ext/mysql extension functions

This is easy to spot - all those mysql_* functions that you are used to. Don't use those anymore, they are completely removed in PHP 7. Few examples are:

  • mysql_connect
  • mysql_query
  • mysql_fetch_assoc

Don't mix variable-variables and the global keyword

below code will produce a parse error:

global $$foo->bar;

All variables is now being evaluated from left-to-right

Yes, prior to PHP 7 it is not like that. It is inconsistent specially for variable-variables and variable-properties.

$object->$array[key];

Prior to PHP 7, PHP will first resolve $array[key] to a string and then access the property named by that string on the $object. It will evaluate differently in PHP7. This kind of logic bugs might be the hardest one to find in your codes thus needs to be extra careful when copy-pasting existing codes.

Don't use PHP 4 Constructors

PHP 4 contructors are constructors that has same name as the class on which it is defined. That means the following should be avoided:


class Foo{
	public function Foo(){}
}

There are lot of new features that comes with PHP 7 and I wont re-iterate those in here. This is more of "survival kit" post so your code is guaranteed to run when the time comes that you need to run it in PHP 7. Those are the "must" when you writing PHP code right now and from this point forward and its up to you if you want to leverage the other new features of PHP 7.


Did you find this useful?

I'm always happy to help! You can show your support and appreciation by Buying me a coffee (I love coffee!).