Skip to main content

PHP 7 Feautures

Performance Battle, PHP 7 vs. PHP 5

With virtually all updates, minor performance upgrades are to be expected. However, this time PHP brings a significant improvement over earlier versions making sheer performance one of PHP 7’s most attractive features. This comes as part of the “PHPNG” project, which tackles the internals of the Zend Engine itself.

By refactoring internal data structures and adding an intermediate step to code compilation in the form of an Abstract Syntax Tree (AST), the result is superior performance and more efficient memory allocation. The numbers themselves look very promising; benchmarks done on real world apps show that PHP 7 is twice as fast as PHP 5.6 on average, and results in 50 percent less memory consumption during requests, making PHP 7 a strong rival for Facebook’s HHVM JIT compiler. Have a look at this infographic from Zend depicting performance for some common CMS and Frameworks.

PHP 7 Syntactic Sugar

PHP 7 comes with new syntax features. While not extending the capabilities of the language itself, they provide a better, or easier, way of making your code more enjoyable to write and pleasing to the eye.

Group Import Declarations

Now, we can group import declarations for classes originating from the same namespace into a single use line. This should help aligning declarations in a meaningful way or simply save some bytes in your files.

use Framework\Module\Foo;
use Framework\Module\Bar;
use Framework\Module\Baz;

With PHP 7 we can use:

use Framework\Module\{Foo, Bar, Baz};
Or, if you prefer a multi-line style:

use Framework\Module{
    Foo,
    Bar,
    Baz
};

Null Coalescing Operator

This solves a common problem in PHP programming, where we want to assign a value to a variable from another variable, if the latter is actually set, or otherwise provide a different value for it. It’s commonly used when we work with user-provided input.

Pre-PHP 7:

if (isset($foo)) {
    $bar = $foo;
} else {
    $bar = 'default'; // we would give $bar the value 'default' if $foo is NULL
}

After PHP 7:

$bar = $foo ?? 'default';
This can be also chained with a number of variables:

$bar = $foo ?? $baz ?? 'default';

Spaceship Operator

The spaceship operator <=> allows for a three way comparison between two values, not only indicating if they are equal, but also which one is bigger, on inequality by returning 1,0 or -1.

Here we can take different actions depending on how the values differ:

switch ($bar <=> $foo) {
    case 0:
        echo '$bar and $foo are equal';
    case -1:
        echo '$foo is bigger';
    case 1:
        echo '$bar is bigger';
}
The values compared can be integers, floats, strings or even arrays. Check the documentation to get an idea of how different values are compared to each other. [https://wiki.php.net/rfc/combined-comparison-operator]

New Features In PHP 7

But of course PHP 7 also brings new and exciting functionality with it.

Scalar Parameter Types & Return Type Hints

PHP 7 extends the previous type declarations of parameters in methods ( classes, interfaces and arrays) by adding the four scalar types; Integers (int), floats (float), booleans (bool) and strings (string) as possible parameter types.

Further, we can optionally specify what type methods and functions return. Supported types are bool, int, float, string, array, callable, name of Class or Interface, self and parent ( for class methods )

class Calculator
{
    // We declare that the parameters provided are of type integer
    public function addTwoInts(int $x, int $y): int {
        return $x + $y; // We also explicitly say that this method will return an integer
    }
}
Type declarations allow the building of more robust applications and avoid passing and returning wrong values from functions. Other benefits include static code analyzers and IDEs, which provide better insight on the codebase if there are missing DocBlocks.

Since PHP is a weakly typed language, certain values for parameter and return types will be cast based on the context. If we pass the value “3” in a function that has a declared parameter of type int, the interpreter will accept it as an integer and not throw any errors. If you don’t want this, you can enable strict mode by adding a declare directive.

declare(strict_types=1);

This is set in a per-file basis, as a global option would divide code repositories to those that are built with global strictness on and those that are not, resulting in unexpected behavior when we combine code from both.

Engine Exceptions

With the addition of engine exceptions, fatal errors that would have resulted in script termination can be caught and handled easily.

Errors such as calling a nonexistent method won’t terminate the script, instead they throw an exception that can be handled by a try catch block, which improves error handling for your applications. This is important for certain types of apps, servers and daemons because fatal errors would otherwise require them to restart. Tests in PHPUnit should also become more usable as fatal errors drop the whole test suite. Exceptions, rather than errors, would be handled on a per test case basis.

To know more about changes click here

Comments

Popular posts from this blog

Generate XML file in Cakephp

Steps to Generate XML file using CakePHP: Step-1 Enable to parse xml extension in config route.php file.     Router::parseExtensions('xml'); Step-2 Add Request Handler Component to the Controller    var $components = array(‘RequestHandler’); Step-3 Add controller Action For XML Generation in Post Controller     function generateXMLFile()     {         if ($this->RequestHandler->isXml()) { // check request type             $this->layout = 'empty'; // create an empty layout in app/views/layouts/empty.ctp              }        }  Add header code in empty layout <?php header('Content-type: text/xml');?> <?php echo $this->Xml->header(); ?> <?php echo $content_for_layout; ?> Step-4 Set up View To generate XML Create xml folder inside Posts vi...

Simple JavaScript Object and Class Examples

In JavaScript, most things are objects. An object is a collection of related data and/or functionality Namespace: Everything you create in JavaScript is by default global. In JavaScript namespace is Global object . How to create a namespace in JavaScript? Create one global object, and all variables, methods, and functions become properties of that object. Example:  // global namespace var MYAPP = MYAPP || {}; Explaination: Here we first checked whether MYAPP is already defined.If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP How to create sub namespaces? // sub namespace MYAPP.event = {}; Class JavaScript is a prototype-based language and contains no class statement.JavaScript classes create simple objects and deal with inheritance. Example: var Person = function () {}; Explaination: Here we define a new class called Person with an empty constructor. Use the class keyword class Calculation {}; A class expr...

How to Add Next Previous links to The Event Calendar

Add Next/Previous links to The Event Calendar Wordpress Plugin Add code to your child theme’s functions.php file /**  * Allows visitors to page forward/backwards in any direction within month view */ if ( class_exists( 'Tribe__Events__Main' ) ) { class ContinualMonthViewPagination {     public function __construct() {         add_filter( 'tribe_events_the_next_month_link', array( $this, 'next_month' ) );         add_filter( 'tribe_events_the_previous_month_link', array( $this, 'previous_month' ) );     }     public function next_month() {         $url = tribe_get_next_month_link();         $text = tribe_get_next_month_text();         $date = Tribe__Events__Main::instance()->nextMonth( tribe_get_month_view_date() );         return '<a data-month="' . $date . '" href="' . $url . '" rel="next"...