Wednesday, March 29, 2017

PHP 7 - Quick Guide

PHP 7 - Introduction

What is PHP 7?

PHP 7 is a major release of PHP programming language and is touted to be a revolution in the way web applications can be developed and delivered for mobile to enterprises and the cloud. This release is considered to be the most important change for PHP after the release of PHP 5 in 2004.

New Features

There are dozens of features added to PHP 7, the most significant ones are mentioned below −
  • Improved performance − Having PHPNG code merged in PHP7, it is twice as fast as PHP 5.
  • Lower Memory Consumption − Optimized PHP 7 utilizes lesser resource.
  • Scalar type declarations − Now parameter and return types can be enforced.
  • Consistent 64-bit support − Consistent support for 64-bit architecture machines.
  • Improved Exception hierarchy − Exception hierarchy is improved.
  • Many fatal errors converted to Exceptions − Range of exceptions is increased covering many fatal error converted as exceptions.
  • Secure random number generator − Addition of new secure random number generator API.
  • Deprecated SAPIs and extensions removed − Various old and unsupported SAPIs and extensions are removed from the latest version.
  • The null coalescing operator (??) − New null coalescing operator added.
  • Return and Scalar Type Declarations − Support for return type and parameter type added.
  • Anonymous Classes − Support for anonymous added.
  • Zero cost asserts − Support for zero cost assert added.
PHP 7 uses new Zend Engine 3.0 to improve application performance almost twice and 50% better memory consumption than PHP 5.6. It allows to serve more concurrent users without requiring any additional hardware. PHP 7 is designed and refactored considering today's workloads.

PHP 7 - Performance

As per the Zend team, following illustrations show the performance comparison of PHP 7 vs PHP 5.6 and HHVM 3.7 on popular PHP based applications.

Magento 1.9

PHP 7 proves itself more than twice as faster, as compared to PHP 5.6 while executing Magento transactions.
Magento Transactions

Drupal 7

PHP 7 proves itself more than twice as faster, as compared to PHP 5.6 while executing Drupal transactions.
Drupal Transactions

Wordpress 3.6

PHP 7 proves itself more than twice as faster as compared to PHP 5.6 while executing Wordpress transactions.
Wordpress Transactions

Comparison of Dynamic Languages

Mandelbrot Transactions

PHP 7 - Environment Setup

Try it Option Online

We have set up the PHP Programming environment on-line, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.
Try the following example using our online compiler available at CodingGround.
<html>
   <head>
      <title>Online PHP Script Execution</title>
   </head>
   <body>
      <?php
         echo "<h1>Hello, PHP!</h1>";
      ?>   
   </body>
</html>
For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just use of and enjoy your learning.
In order to develop and run PHP Web pages, three vital components need to be installed on your computer system.
  • Web Server − PHP works with virtually all Web Server software, including Microsoft's Internet Information Server (IIS) but most often used is Apache Server. Download Apache for free here − http://httpd.apache.org/download.cgi
  • Database − PHP PHP works with virtually all database software, including Oracle and Sybase but most commonly used is MySQL database. Download MySQL for free here − http://www.mysql.com/downloads/
  • PHP Parser − In order to process PHP script instructions, a parser must be installed to generate HTML output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on your computer.

PHP Parser Installation

Before you proceed, it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Store the following php file in Apache's htdocs folder.

phpinfo.php

<?php
   phpinfo();
?>
Type the following address into your browser's address box.
http://127.0.0.1/phpinfo.php
If this displays a page showing your PHP installation related information, then it means you have PHP and Webserver installed properly. Otherwise, you have to follow the given procedure to install PHP on your computer.
This section will guide you to install and configure PHP over the following four platforms −

Apache Configuration

If you are using Apache as a Web Server, then this section will guide you to edit Apache Configuration Files.
Check here − PHP Configuration in Apache Server

PHP.INI File Configuration

The PHP configuration file, php.ini, is the final and immediate way to affect PHP's functionality.
Check here − PHP.INI File Configuration

Windows IIS Configuration

To configure IIS on your Windows machine, you can refer your IIS Reference Manual shipped along with IIS.

PHP 7 - Scalar Type Declarations

In PHP 7, a new feature, Scalar type declarations, has been introduced. Scalar type declaration has two options −
  • coercive - coercive is default mode and need not to be specified.
  • strict - strict mode has to explicitly hinted.
Following types for function parameters can be enforced using the above modes −
  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable

Example - Coercive Mode

<?php
   // Coercive mode
   function sum(int ...$ints) {
      return array_sum($ints);
   }
   print(sum(2, '3', 4.1));
?>
It produces the following browser output −
9

Example - Strict Mode

<?php
   // Strict mode
   declare(strict_types=1);
   function sum(int ...$ints) {
      return array_sum($ints);
   }
   print(sum(2, '3', 4.1));
?>
It produces the following browser output −
Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, ...

PHP 7 - Return Type Declarations

In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.
  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable

Example - Valid Return Type

<?php
   declare(strict_types = 1);
   function returnIntValue(int $value): int {
      return $value;
   }
   print(returnIntValue(5));
?>
It produces the following browser output −
5

Example - Invalid Return Type

<?php
   declare(strict_types = 1);
   function returnIntValue(int $value): int {
      return $value + 1.0;
   }
   print(returnIntValue(5));
?>
It produces the following browser output −
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...

PHP 7 - Null Coalescing Operator

In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

Example

<?php
   // fetch the value of $_GET['user'] and returns 'not passed'
   // if username is not passed
   $username = $_GET['username'] ?? 'not passed';
   print($username);
   print("<br/>");

   // Equivalent code using ternary operator
   $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
   print($username);
   print("<br/>");
   // Chaining ?? operation
   $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
   print($username);
?>
It produces the following browser output −
not passed
not passed
not passed

PHP 7 - Spaceship Operator

In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

Example

<?php
   //integer comparison
   print( 1 <=> 1);print("<br/>");
   print( 1 <=> 2);print("<br/>");
   print( 2 <=> 1);print("<br/>");
   print("<br/>");
   
   //float comparison
   print( 1.5 <=> 1.5);print("<br/>");
   print( 1.5 <=> 2.5);print("<br/>");
   print( 2.5 <=> 1.5);print("<br/>");
   print("<br/>");
   
   //string comparison
   print( "a" <=> "a");print("<br/>");
   print( "a" <=> "b");print("<br/>");
   print( "b" <=> "a");print("<br/>");
?>
It produces the following browser output −
0
-1
1

0
-1
1

0
-1
1

PHP 7 - Constant Arrays

Array constants can now be defined using the define() function. In PHP 5.6, they could only be defined using const keyword.

Example

<?php
   //define a array using define function
   define('animals', [
      'dog',
      'cat',
      'bird'
   ]);
   print(animals[1]);
?>
It produces the following browser output −
cat

PHP 7 - Anonymous Classes

Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.

Example

<?php
   interface Logger {
      public function log(string $msg);
   }

   class Application {
      private $logger;

      public function getLogger(): Logger {
         return $this->logger;
      }

      public function setLogger(Logger $logger) {
         $this->logger = $logger;
      }  
   }

   $app = new Application;
   $app->setLogger(new class implements Logger {
      public function log(string $msg) {
         print($msg);
      }
   });

   $app->getLogger()->log("My first Log Message");
?>
It produces the following browser output −
My first Log Message

PHP 7 - Closure::call()

Closure::call() method is added as a shorthand way to temporarily bind an object scope to a closure and invoke it. It is much faster in performance as compared to bindTo of PHP 5.6.

Example - Pre PHP 7

<?php
   class A {
      private $x = 1;
   }

   // Define a closure Pre PHP 7 code
   $getValue = function() {
      return $this->x;
   };

   // Bind a clousure
   $value = $getValue->bindTo(new A, 'A'); 

   print($value());
?>
It produces the following browser output −
1

Example - PHP 7+

<?php
   class A {
      private $x = 1;
   }

   // PHP 7+ code, Define
   $value = function() {
      return $this->x;
   };

   print($value->call(new A));
?>
It produces the following browser output −
1

PHP 7 - Filtered unserialize()

PHP 7 introduces Filtered unserialize() function to provide better security when unserializing objects on untrusted data. It prevents possible code injections and enables the developer to whitelist classes that can be unserialized.

Example

<?php
   class MyClass1 { 
      public $obj1prop;   
   }
   class MyClass2 {
      public $obj2prop;
   }

   $obj1 = new MyClass1();
   $obj1->obj1prop = 1;
   $obj2 = new MyClass2();
   $obj2->obj2prop = 2;

   $serializedObj1 = serialize($obj1);
   $serializedObj2 = serialize($obj2);

   // default behaviour that accepts all classes
   // second argument can be ommited.
   // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object
   $data = unserialize($serializedObj1 , ["allowed_classes" => true]);

   // converts all objects into __PHP_Incomplete_Class object except those of MyClass1 and MyClass2
   $data2 = unserialize($serializedObj2 , ["allowed_classes" => ["MyClass1", "MyClass2"]]);

   print($data->obj1prop);
   print("<br/>");
   print($data2->obj2prop);
?>
It produces the following browser output −
1
2

PHP 7 - IntlChar

In PHP7, a new IntlChar class is added, which seeks to expose additional ICU functionality. This class defines a number of static methods and constants, which can be used to manipulate unicode characters. You need to have Intl extension installed prior to using this class.

Example

<?php
   printf('%x', IntlChar::CODEPOINT_MAX);
   print (IntlChar::charName('@'));
   print(IntlChar::ispunct('!'));
?>
It produces the following browser output −
10ffff
COMMERCIAL AT
true

No comments:

Post a Comment