PHP 7: the main news

0
340

Why PHP 7?

PHP 6 will never see the light, to confirm it there is the recent release of the Alpha version of PHP 7; the last stable update of the well-known Open Source language for server-side scripting was PHP 5.6 followed by some minor upgrades, so what was the reason for this transition to release number 7? The reasons behind this choice should be sought in the features that the developers of the project had intended to introduce in PHP 6.

Among them the most important was certainly the implementation of a native support suitable for the standard Unicode encoding, but this would have proved immediately too expensive in terms of resources, without taking into account the negative effect on the recorded performance during the tests; the project was then aborted and, called to decide on the name of the new language version, the project managers would have opted for a large majority for PHP 7, underlining the differences between the branch that was never born and the next.

The same goes for PHP 5.7; PHPNG ( PHP New Generation ), which is the basis of PHP 7, was initially interpreted as an alpha of the latter, but the work done in terms of additional features integration with regard to performance, he convinced developers to launch a new major release.

The Spaceship Operator

The Spaceship Operator , or combined comparison operator, is represented by a sequence composed of three symbols, “<=>”, and works relatively similar to the native function strcmp()for the case-sensitive comparison of strings, but has the particularity of being able to be used with any type of data supported by PHP; at the construct level it requires a syntax identical to that of any other comparison operator and returns “0” in case the operands are equal to each other, “1” if the left operand is the largest and “- 1 “if to be greater the right operand is instead.

Wanting to make a simple example based on decimal numerical values ( float), we could perform a check on the operation of this operator based on the instructions for video printing:

// returns 0
echo 7.3 &amp;lt;=&amp;gt; 7.3;
// returns 1
echo 7.3 &amp;lt;=&amp;gt; 3.7;
// return -1 
echo 3.7 &amp;lt;=&amp;gt; 7.3;

What has already been said can be repeated following the same logic also for a type of data different from the one analyzed above, the strings, which respect a hierarchy not based on the entity of values, but on a priority order:

// returns 0
echo "x" &amp;lt;=&amp;gt; "x";
// returns 1
echo y &amp;lt;=&amp;gt; x;
// return -1 
echo x &amp;lt;=&amp;gt; y;

Since it xis equal to itself, the first statement will return 0, instead it will return 1 in the second case because it yis later than (and therefore larger than) xand -1 in the third case because it xis less than y; arrays and objects will be managed in the same way shown in the examples.

The Spaceship Operator could be particularly useful in cases where comparisons must be used within complex expressions based on conditions; in this regard, refer to the following example

function space_ship($x, $y) {
    return ($x &amp;lt; $y) ? -1 : (($x &amp;gt; $y) ? 1 : 0);
}

By translating the expression that represents the return value of the function, it would be that in case $x(left operand) is less than $y(right operand) then -1 would be TRUE, if, on the contrary, it $xwas greater than $yto be TRUE it would be 1; alternatively, and therefore only in the case of an identity of values, 0 would be returned. The previously proposed code and the above reasoning could therefore be abbreviated as follows:

function space_ship($x, $y) {
    return $x &amp;lt;=&amp;gt; $y;
}

In fact, the introduction of the combined comparison operator is also an opportunity to make the sources shorter and more readable.

From Elvis to the null coalescing operator

PHP 7 presents a new logical operator, the null coalescing operator, which can now also be used in this as in other languages within conditional expressions. To understand its usefulness it is necessary to remember that, starting from the 5.3 release, it has been introduced the possibility of shortening the syntax of the ternary operator in some cases, making the symbols?(TRUE) and :(FALSE) concomitant and removing the argument that divided; reason for which to an expression like the following:

$ x = $ y? 
$ y: $ z;

It was possible to replace a condition typed in this way:

$ x = $ y?: $ z;

In practice, both proposed codes correspond to:

if ($ x) {
    $ y = $ x;
} else {
    $ y = $ z;
}

?:takes the name of Elvis operator and is a conditional operator that can also be used to self-check variables using a syntax similar to that of the previously proposed instructions; in this regard, analyze the following code where it $zwill be assigned to $xif the latter is NULL or FALSE, otherwise it $xwill remain unchanged.

$ x = $ x?: $ z;

The null coalescing operator of PHP 7, ?? works very similar to the Elvis operator, in an expression it will return the left operand if this is not NULL, if this condition does not occur the right operand will be returned. Please note that the operator will not produce an exception report if the left operand is non-existent, which is why an even more correct comparison could be related to its points in common with the function isset(), which determines if a variable is been defined and is not NULL; in practice it ??allows to perform limited checks on variables (or other constructable constructs such as arrays) that are NULL or non-existent. An example regarding the use of this operator could be the following:

$w = $x ?? $y ?? $z;

The expressed condition is substantially translatable in this way: if it $xexists and is not NULL then it $wis equal to $x, otherwise, if it $yexists and it is not NULL then it $wis equal to $y, otherwise it $wwill be equal to $z. To report what was said by the classic ternary operator would have served an instruction like the following:

$w = (isset($x) ? $x : (isset($y) ? $y : $z));

The advantage deriving from the use of the null coalescing operator, therefore, appears evident also in terms of time savings in typing the listing and lightness of the sources.

The anonymous classes

Among the features most requested by the developers who complained about the limitations in supporting the object-oriented paradigm of PHP were the anonymous classes ( Anonymous Classes ), now present in version 7 of the language; up to this last release the only possibility to exploit this type of constructs was to simulate them through the use of the closures, but this methodology did nothing but emphasize the gaps of PHP compared to other solutions like Java.

In essence, the anonymous classes are none other than classes characterized not only by the fact that they lack a name defined in the programming, but also by the phases of declaration and instance that, in this particular case, occur simultaneously; they could be useful when you need to use a class only once in the course of execution, in the same way the Anonymous Classes represent a viable alternative when there is no need to document classes.

The syntax of anonymous classes is based on the use of the keyword new, the following example regards the generation of an object of an anonymous class that specifically does not operate some extension from another class nor does it implement interfaces.

$obj = new class("Java") {
    public function __construct($linguaggio) {
        $this-&amp;gt;linguaggio = $linguaggio;
    }
};

Clearly, in this new type of classes there is no lack of support for inheritance ; just as it happens with classes with a name, in this case too the keyword will be used extends, but using a syntax on the model of the one proposed by the following example:

$obj = new class("Java")
extends Programmazione {
    public function __construct($linguaggio) {
        $this-&amp;gt;linguaggio = $linguaggio;
    }
};

In the same way, there will be the possibility to implement interfaces through the Anonymous Classes using the already known keyword implements:

interface Informatica {
    public function method();
}
$obj = new class("Java")
extends Programmazione implements Informatica {
    public function __construct($linguaggio) {
        $this-&amp;gt;linguaggio = $linguaggio;
    }
    public function method() {}
};

The developers of PHP would have decided not to insert in the language of the new keywords for the use of anonymous classes, this to avoid the occurrence of conflicts ensuring the backward compatibility.

Declaration of scalar data types

Another new feature of PHP 7 is the introduction of elements for the declaration of scalar data types ; in this language scalar variables are defined as those that contain values associated with the types integer, float, stringor bool, while they are non-scalar types array, objectand resource. Given the many criticisms from the community regarding the implementation of this feature, the developers decided to devise a system for declaring the types identical to the one already in use.

To explain this in detail, it is possible to refer to the type-hint system (or “type suggestion”) that in PHP default mode is non-strict , this means that type evaluations are delegated to expressions ( lazy evaluation ); to give an example, the passage of int(2)an expression that requires a decimal value will result in an interpretation equal to float(2.0), while float(7.2)passed to a function that requires an integer will lead to interpreting the data as int(7).

The declaration of scalar types does not introduce new reserved in PHP terms, so that you can continue to use integer, float, stringor bool, for enable mode strict , however, it is available the following directive for the type-checking :

declare(strict_types=1);

The latter must be the first instruction entered in a file, if positioned in another way it will give rise to an error notification; a simple example regarding its use could be the following:

declare(strict_types=1);
homer(); 
function simpson() {
    homer(); 
}
class springfield {
    function simpson() {
        homer(); 
    }
}

In this case, the strict mode directive will affect all calls to the function homer(), including those made from within an additional function or method.

Declaration of the type of return data

The declaration of the type of return data is a new feature closely related to the declaration of the scalar data types and works on the basis of the same mechanism, also in this case the 1-value evaluation of the directive will strict_typesallow to perform type-checking operations in strict mode ; in this regard, analyze the syntax of the snippet proposed below.

declare(strict_types=1);
function intero(): int {
    return 2.0; 
}
class cifre {
    function intero(): int {
        return 2.0; 
    }
}

In the previous example to the one just proposed, it is possible to see how, in the parameter declarations, it strict_typesacts where a call to the function occurs; in the declaration of the type of return data the directive will instead be applied in the file in which the function has been defined, so it will not depend on a possible passage of parameters to the function. For this reason, the following function will return a return value that has been associated with a default type before its call:

function returnType(int $type): bool {
    return isset($this-&amp;gt;types[$type]);
}

Basically in the function a simple operation is performed based on the Return Type Hint (or “return type suggestion”) for which the function will returnType()return a boolean as indicated by : bool.

Engine Exceptions for fatal errors

As is known, PHP manages the error types based on 4 groups proposed here in order of increasing gravity: notices , warnings , recoverable fatal and fatal ; up to PHP 7 the latter were difficult to manage due to the fact that they were not designed to invoke the exception handler ( error handler ), which is why their occurrence still led to an unexpected interruption, and especially immediate, of the script being executed.

With the last major release of the language, we tried to fill this gap by introducing appropriate Object-based Engine Exceptions\EngineException. The following example will show a typical case of failure to handle a fatal error , ie that of passing a NULL parse to a method:

function mostra_errore($oggetto) {
    $oggetto-&amp;gt;method();
} 
mostra_errore(null);

The result expected at runtime will therefore be the notification:

Fatal error: Call to a member function method() on a non-object in /../nomefile.php on line 4

Thanks to the PHP 7 Engine Exceptions you can instead use a syntax like the following:

try {
    mostra_errore(null);
} catch (EngineException $e) {
    echo "Attenzione: {$e-&amp;gt;getMessage()}\n";
}

It is clear that the Engine Exceptions do not operate automatically when a fatal error occurs, which is why it will be necessary to adopt them in a block try/catch, otherwise the result of the execution will be the failure to handle the error.

The Closure-> call method

With version 5.4 the method has been introduced in PHP Closure::bindTo, as well as its static variant Closure::bind, which in practice has the task of duplicating a closure through a new association to the object and to the class visibility; in essence there is the possibility to return a new anonymous function characterized by the same body and by the same variables of the original, instead they change the object associated with it, which defines the value of the pseudovariable $this, and the visibility of the class, ie the reference to the access level of the function to the members privatee protected.

In PHP 7 we now have the new method Closure->call()that simplifies the binding procedures for the closures at the time of the call; a simple example concerning the use of this method could be written in this way:

class NomeCognome {
     private $nome = "Homer";
}
$closure = function($cognome) { 
     echo $this-&amp;gt;nome . ' ' . $cognome; 
}
$obj = new NomeCognome();
$closure-&amp;gt;call($obj, 'Simpson');

Substantially it Closure->call()makes a call to the closure on the basis of the data parameters and returns the expected result, which in the case of the previous example is in practice the concatenation between the values of two variables, maintaining the link between the pseudovariable $thisand the associated object.

Performance and support

As you can see, the news in PHP 7 are numerous, but according to most of the exponents of the community that revolves around the language the most important feature of this update should not be sought in the additional features, but in the level of performance achieved: PHP 7 it should in fact guarantee a double execution speed compared to PHP 5.6; among the other implementations present it is possible to mention the interventions made to support the 64-bit architectures, the removal of the mysql functions long deprecated and the incompatibility with the use of the “ASP style” (” <% .. %>”) and “JavaScript” delimiters style “(” <script language=php>..</script>”) previously allowed.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here