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

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

Integrating Kafka with Node.js

Integrating Kafka with Node.js Apache Kafka is a popular open-source distributed event streaming platform that uses publish & subscribe mechanism to stream the records(data). Kafka Terminologies Distributed system: Distributed system is a computing environment where various software components located on different machines (over multiple locations). All components coordinate together to get stuff done as one unit.   Kafka Broker: Brokers are cluster of multiple servers. Message of each topic are split among the various brokers. Brokers handle all requests from clients to write and read events. A Kafka cluster is simply a collection of one or more Kafka brokers. Topics: A topic is a stream of "related" messages. Its unique throughout application. Kafka producers write messages to topics. Producer: Producer publishes data on the topics. A producer sends a message to a broker and the broker receives and stores messages. Consumers: Consumers read data from topics. A consu...