PHP 7 in-depth Look

PHP 7 in-depth Look

 

PHP 7 was released on 03 Dec 2015, and so many people have not yet started using or learning about the awesome features it has. I wrote this post to give a breakdown of the features released with PHP 7 for those that have not yet learnt about them and even if you know it, you might still learn something from this post.

Rasmus Lerdorf(creator of PHP) claims that apps running PHP 7 performance is improved by 100% or more. Memory usage is lower also, so if you are running a lot of servers, PHP 7 is an essential upgrade. One of the big changes in PHP 7 is the refactored ZEND Engine(PHPNG) which is now faster, memory usage reduced and a “green” version of PHP which makes you run less hardware to run your code.

So what has been removed from PHP 7?
  1. MYSQL:
    Original MySQL extension was deprecated in PHP 5.5. We used functions such as mysql_connect(), mysql_query(). It is highly recommended to use the improved MYSQL – MySQLi or PDO for any database related operations. If you start using PHP 7 (which you should start ASAP), this extension has been removed totally. But if you want to make use of MySQL extension, you can find and install it at https://pecl.php.net/ . PECL is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.
  2. POSIX REGEX FUNCTIONS:
    PHP offers functions that are specific to a certain kind of regular expression – POSIX Regular functions and PERL Style Regular Expression. With PHP 7 you cannot use POSIX functions such as ereg(), ereg_replace(), split(), but instead you should use PERL-compatible Regex(PCRE) functions such as preg_match(), preg_replace(), preg_split(). If you still need the POSIX REGEX functions in your app, you can also install them from https://pecl.php.net/
  3. ALTERNATIVE PHP TAGS:
    In PHP 7, you can no longer wrap ASP tags such as <% %> or <%= %> and HTML script tags <script languages=”php”></script>.
  4. ASSIGNMENT OF NEW BY REFERENCE:
    This is no longer possible with PHP 7 $car =& new Car(); This was not really necessary in PHP 5 because objects are always created by reference.
  5. COMMENTS IN CONFIGURATION FILES:
    This was deprecated in PHP 5.3 but with PHP 7, you can no longer use ‘#’ for comments in your .ini files. The required character is the standard semicolon ‘;’
  6. SALT OPTION IN PASSWORD_HASH():
    The salt option for password_hash() has been deprecated to prevent developers from creating their own salt which may not be secure.

You can learn more here https://wiki.php.net/rfc/remove_deprecated_functionality_in_php7

So with all these gone in PHP 7, what are the new features now? These are the new features in PHP 7:

The Spaceship Operator <=>
The spaceship operator (aka combined comparison operator) is used for comparing two expressions. It will return -1, 0, or 1 when the left expression is less than the right expression. This can also work with strings. This is mostly used in callback functions such as in custom sorting of values.

The Null Coalescing Operator ??
With the null coalescing operator, there is no need to use functions such as isset(). It simply returns the first operand if it not null, else it returns the last. We can also chain values with this feature. It uses the first non-null value it comes across starting from the left. Note that this is for null values only and not empty string which is not null in PHP.

Constant Arrays Using define()
Array constants can now be defined with define(). In PHP 5.6, they could only be defined with const.

Unicode Escape Sequence(Emoji support)
We all love some nice emojis to communicate with our friends, with PHP 7 you can now use emoji in your application. You can visit this link to view emojis possible.
echo "PHP 7 has smiley! \u{1F600}";

Integer Division intdiv()
With integer division function – intdiv(), you get the result of a division operation as integer instead of casting the result to int which can perform the same function.

Random Bytes random_bytes()
This creates a string of random bytes. You give it the length of the bytes pass in as a parameter. This can be use to generate unpredictable values for cookies. Use together with bin2hex() to print out a hexadecimal string.

Random Integer random_int(int $min, int $max)
This create a random integer using a cryptographically strong random generator.

1.0 PHP 7 TYPE CHECKING

Return Type Declarations Compound Types
The advantages of using this include: prevention of unintended return values, forces subclasses to return expected data type, document return type information in robust way. This is very similar to type casting in Java. This will trigger a fatal error if the return type is not what you stated. Declaring a return type is optional in PHP 7. The following data types can be used: class name/Interface name, array, callable, bool, float, int, string, self and parent.

Scalar Type Hinting
PHP has four scalar types: Boolean, Integer, Float and String. Scalar types are used to identify just a single value. The valid data types are bool, int, float and string. The syntax is similar to the compound types we discussed above. Scalar types in PHP 7 has two modes – weak(default) and strict(must be stated explicitly).
Weak Mode: Data types are converted automatically eg Strings are converted to integers or float is need be. This disadvantage of this is that you might get unexpected results. In this mode, parameters are cast to the specified data type.
Strict Mode: Data types are enforced. Must be enabled or declared in the file. You declare(strict_types=1) as the first statement in your PHP file. Note that this does not affect the code in an include file or parent file. Just know that parameters must match the specified type in a strict mode.


Strict mode affects built-in PHP functions, so you need to be careful because this can cause unexpected results.

2.0 CLASSES AND GENERATORS

Anonymous Classes
In PHP 5.6, we had anonymous functions. In PHP 7, we now have anonymous classes. Anonymous class does not have a name but you can assign it to a variable, return it from a function, pass it an argument to a function, extend a class, implement an interface and make use of traits. The drawback is that you cannot serialize an anonymous class.
Typical uses can be when the class does not need to be documented, use just once or unit testing.

Generator Return Expression
Generators were included in PHP 5.5, it was a simple way to iterate over large sets of data without consuming much memory. In PHP 7, you can now return a value from a generator with $generator->getReturn()

Generator Delegation
In generator delegation, you can call a generator within another generator and yield the values. The generator inside another generator is called a sub-generator.

Closure
Instead of using Closure::bindTo which duplicates the closure with a new bound object and class scope. In PHP 7, you can use Closure::callwhich binds and calls the closure. Using Closure::call, there is no need to specify the class name to bind that class scope of $this, it automatically detects it and bind it for you.

Group Use
This is used when importing multiple classes, functions or constants from a common namespace. This makes you code cleaner and well structured. You can even mix classes, functions and constants from the same namespace.

3.0 ERROR HANDLING

Catching fatal errors
PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions. If you run the code in the example below in pre PHP 7, the finally block is not called and also the _destruct() too. If you then run it in PHP 7, the finally block will be executed but the exception thrown is not caught in the Exception catch block but instead in the Error catch block because fatal errors are not exceptions but in a class of their own called Error and because we caught the error the __destruct() is called.

Throwable Interface
PHP 7 throws most fatal errors as exceptions which can be caught in a try block. Exceptions and errors does not belong in the same class in PHP 7 but instead different classes. Exception and Error class both implements the Throwable interface. This implies that they have the same methods such as getMessage(), getCode(), getFile(), getLine(), getTrace(), _toString() etc and behave in a very similar ways. There are three sub-classes that extends the Error class which are:

TypeError: This is thrown when a function argument or return data type does not match the type declaration.
ParseError: This is triggered when an include file or PHP code passed to eval() includes a syntax error.
AssertionError: Fired when a condition set my assert() fails. For assertion errors to be thrown, in your php configuration file, set zend.assertion = 1 and assert.exception = 1

To create you own custom errors or exceptions class, you must extend Error or Exception class, you cannot implement the Throwable interface directly. Throwable can be extended to add new methods then you can implement your extended interface.

New Reserved Words
PHP 7 now has new reserved words such as int, float, bool, string, true, false, null, resource, object, mixed and numeric. Shocked? Me too!. Aliases such as integer, double and boolean are not reserved.

Defaults In Switch Statements
There is in bug or a feature in pre PHP 7 versions, this bug makes it possible to add multiple default cases in a switch statement but in PHP 7+, this will cause a compile error.

4.0 Misc Changes

There have been significant improvement in functions such as:
unserialize(string $str [, array $options ]): Use to prevent PHP object injection (you can read about it here and the PHP documentation here).
json_encode($value): In pre PHP 7, If you have a floating point number value in your $value variable, json_encode($value) remove the fractional part if it is 0 and convert it into an integer. In PHP 7+, a new PHP constant – JSON_PRESERVE_ZERO_FRACTION allows you to preserve zero fraction.

Semi Reserved Words
Words such as abstract, and, case, array, as, break, callable, case, catch, clone, const, continue, declare, default, die, do, echo, else, elseif, enddeclare, endfor, endforeach, endif, endswitch, endwhile, exit, extends, final, finally, for, foreach, function, global, goto, if, implements, include, include_once, instanceof, instedof, interface, list, namespace, list, new, or, parent, print, private, protected, public, require, require_once, return, self, static, switch, throw, trait, try, use, var, while, xor, yield can now be used as constants and method names(though it is not recommended to use) in you defined classes from PHP 7+ but will fire a syntax error if used in pre PHP 7. The only reserved word globally is ‘class’ which you cannot use.

With this new information at your disposal when you want to start a new PHP project make sure you use PHP 7 or you can migrate your existing projects from PHP 5.6.x to PHP 7.0.X by visiting this guide to do that.

Thanks for reading. If you like this post, please feel free to recommend this to other people. kindly share this or share your thoughts in the comment section below.

Cheers.

References and further reading
http://php.net/manual/en/migration70.new-features.php

SHARE ON
  • Wan

    Awesome! This is a real great piece..Would definitely try out Php 7 now..Thanks for sharing..

    • Mgbemena Chike

      Thanks for reading! You are welcome

  • Robert Diaz

    This should be a mini pocket book! Thanks

    • Mgbemena Chike

      You are welcome! Thanks

  • Excellent write up, and good to have it in one place. Have been trying to think where anonymous classes might have much of a use, but throw-aways in testing is all I can come up with. Anyone else got anything else they’re useful for?

  • gidkom

    Great piece you put together man!!!

    • Mgbemena Chike

      thanks man!!!

  • Damian

    Hi. Great article. Thanks. Found one typo: “TypeError: This is thrown when a fucntion argument or return data type does not match the type declaration.” Fucntion 😊

    • Mgbemena Chike

      Thanks! It has been corrected

  • Saif Ansari

    This help to increase my interest of learning php7. Such a good article…

  • Дмитрий Иванов

    This is really awesome and useful! Thank you and good luck to you!

  • Great work dear. It helps a lot. God bless you.