PHP 7 - Quick Guide


Advertisements

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

PHP 7 - CSPRNG

In PHP 7, following two new functions are introduced to generate cryptographically secure integers and strings in a cross platform way.

  • random_bytes() − Generates cryptographically secure pseudo-random bytes.

  • random_int() − Generates cryptographically secure pseudo-random integers.

random_bytes()

random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

Syntax

string random_bytes ( int $length )

Parameters

  • length − The length of the random string that should be returned in bytes.

Return Values

  • Returns a string containing the requested number of cryptographically secure random bytes.

Errors/Exceptions

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.

  • If invalid parameters are given, a TypeError will be thrown.

  • If an invalid length of bytes is given, an Error will be thrown.

Example

<?php
   $bytes = random_bytes(5);
   print(bin2hex($bytes));
?>

It produces the following browser output −

54cc305593

random_int()

random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical.

Syntax

int random_int ( int $min , int $max )

Parameters

  • min − The lowest value to be returned, which must be PHP_INT_MIN or higher.

  • max - The highest value to be returned, which must be less than or equal to PHP_INT_MAX.

Return Values

  • Returns a cryptographically secure random integer in the range min to max, inclusive.

Errors/Exceptions

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.

  • If invalid parameters are given, a TypeError will be thrown.

  • If max is less than min, an Error will be thrown.

Example

<?php
   print(random_int(100, 999));
   print(" ");
   print(random_int(-1000, 0));
?>

It produces the following browser output −

614
-882

PHP 7 - Expectations

Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails. assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested.

Configuration directives for assert()

Directive Default value Possible values
zend.assertions 1

1 − generate and execute code (development mode)

0 − generate code but jump around it at runtime

-1 − do not generate code (production mode)

assert.exception 0

1 − throw, when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception was not provided.

0 − use or generate a Throwable as described above, but only generates a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

Parameters

  • assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.

  • description − An optional description that will be included in the failure message, if the assertion fails.

  • exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled.

Return Values

FALSE if the assertion is false, TRUE otherwise.

Example

<?php
   ini_set('assert.exception', 1);

   class CustomError extends AssertionError {}

   assert(false, new CustomError('Custom Error Message!'));
?>

It produces the following browser output −

Fatal error: Uncaught CustomError: Custom Error Message! in...

PHP 7 - use Statement

From PHP7 onwards, a single use statement can be used to import Classes, functions and constants from same namespace instead of multiple use statements.

Example

<?php
   // Before PHP 7
   use com\howcodex\ClassA;
   use com\howcodex\ClassB;
   use com\howcodex\ClassC as C;

   use function com\howcodex\fn_a;
   use function com\howcodex\fn_b;
   use function com\howcodex\fn_c;

   use const com\howcodex\ConstA;
   use const com\howcodex\ConstB;
   use const com\howcodex\ConstC;

   // PHP 7+ code
   use com\howcodex\{ClassA, ClassB, ClassC as C};
   use function com\howcodex\{fn_a, fn_b, fn_c};
   use const com\howcodex\{ConstA, ConstB, ConstC};

?>

PHP 7 - Error Handling

From PHP 7, error handling and reporting has been changed. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, now most errors are handled by throwing Error exceptions. Similar to exceptions, these Error exceptions bubble up until they reach the first matching catch block. If there are no matching blocks, then a default exception handler installed with set_exception_handler() will be called. In case there is no default exception handler, then the exception will be converted to a fatal error and will be handled like a traditional error.

As the Error hierarchy is not extended from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will not handle such errors. A catch (Error $e) { ... } block or a set_exception_handler() handler is required to handle fatal errors.

Exception Hierarchy

Example

<?php
   class MathOperations {
      protected $n = 10;

      // Try to get the Division by Zero error object and display as Exception
      public function doOperation(): string {
         try {
            $value = $this->n % 0;
            return $value;
         } catch (DivisionByZeroError $e) {
            return $e->getMessage();
         }
      }
   }

   $mathOperationsObj = new MathOperations();
   print($mathOperationsObj->doOperation());
?>

It produces the following browser output −

Modulo by zero

PHP 7 - Integer Division

PHP 7 introduces a new function intdiv(), which performs integer division of its operands and return the division as int.

Example

<?php
   $value = intdiv(10,3);
   var_dump($value);
   print(" ");
   print($value);
?>

It produces the following browser output −

int(3) 
3

PHP 7 - Session Options

From PHP7+, session_start() function accepts an array of options to override the session configuration directives set in php.ini. These options supports session.lazy_write, which is by default on and causes PHP to overwrite any session file if the session data has changed.

Another option added is read_and_close, which indicates that the session data should be read and then the session should immediately be closed unchanged. For example, Set session.cache_limiter to private and set the flag to close the session immediately after reading it, using the following code snippet.

<?php
   session_start([
      'cache_limiter' => 'private',
      'read_and_close' => true,
   ]);
?>

PHP 7 - Deprecated Features

Following features are deprecated and may be removed from future releases of PHP.

PHP 4 style constructors

PHP 4 style Constructors are methods having same name as the class they are defined in, are now deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes implementing a __construct() method are unaffected.

Example

<?php
   class A {
      function A() {
         print('Style Constructor');
      }
   }
?>

It produces the following browser output −

Deprecated: Methods with the same name as their class will not be constructors 
in a future version of PHP; A has a deprecated constructor in...

Static calls to non-static methods

Static calls to non-static methods are deprecated, and may be removed in the future.

Example

<?php
   class A {
      function b() {
         print('Non-static call');
      }
   }
   A::b();
?>

It produces the following browser output −

Deprecated: Non-static method A::b() should not be called statically in...
Non-static call

password_hash() salt option

The salt option for the password_hash() function has been deprecated so that the developers do not generate their own (usually insecure) salts. The function itself generates a cryptographically secure salt, when no salt is provided by the developer - thus custom salt generation is not required any more.

capture_session_meta SSL context option

The capture_session_meta SSL context option has been deprecated. SSL metadata is now used through the stream_get_meta_data() function.

PHP 7 - Removed Extensions & SAPIs

Following Extensions have been removed from PHP 7 onwards −

  • ereg
  • mssql
  • mysql
  • sybase_ct

Following SAPIs have been removed from PHP 7 onwards −

  • aolserver
  • apache
  • apache_hooks
  • apache2filter
  • caudium
  • continuity
  • isapi
  • milter
  • nsapi
  • phttpd
  • pi3web
  • roxen
  • thttpd
  • tux
  • webjames
Advertisements