What the hell is PHP7?
PHP7 is a major version of the PHP programming language and boasts a revolution in the development of Web applications that can be developed and delivered to mobile companies and cloud applications. This version is considered to be the most important change after PHP released PHP5 in 2004.
New features
PHP7 has added dozens of features, most notably the following mentioned-
Improved performance –phpng code is merged in PHP7, which is twice times faster than PHP5;
Reduced memory consumption – optimized PHP7 uses fewer resources;
Scalar type declaration – now, parameter and return value types can be enforced;
Consistent 64-bit support – 64-bit architecture machine continuous support;
Improved exception hierarchies – exception hierarchies improved;
Many fatal errors are converted to exceptions-the scope of the exception increases to cover many fatal error conversion exceptions;
Safe Random number generator – Adding a new security random number generator API;
Obsolete APIs and extended deletions – different old and unsupported applications and extensions, removed from the latest version;
Null merge operator (?? The new null merge operator is added;
Returns and scalar type declarations support return types and parameter types are also added;
Increased support for anonymous anonymous classes;
0 Cost statement supports 0 cost added assertion.
PHP7 uses the new Zend Engine 3.0 to increase application performance by twice times, a 50% lower memory consumption than PHP5.6. It can serve more concurrent users without any additional hardware. Consider today's workload PHP7 design and refactoring.
php7– Performance
According to the Zend Development team, the following figure shows the performance of popular PHP based applications PHP7 compared to PHP5.6 on 3.7 hhvm.
Magento 1.9
The Magento transaction performed is twice times faster than PHP5.6,PHP7.
Magento transactions
Drupal 7
PHP5.6,PHP7 proved to be twice times faster than performing Drupal transactions.
Drupal transactions
WordPress 3.6
PHP7 proves that he is twice times faster than PHP5.6 because it compares to performing WordPress transactions.
Wordpress transactions
Comparison of Dynamic languages
Mandelbrot transactions
php7– Environment settings
In order to develop and run a PHP Web page, you need to install three important components on your computer system.
Web server −php can work with almost all Web server software, including Microsoft's Internet Information Server (IIS), but the most common is the free Apache server. Download apache−http://httpd.apache.org/download.cgi here for free
Database −php can work with almost all of the database software, including Oracle and Sybase, but the most common is the free MySQL database. MySQL is here for free download at −http://www.mysql.com/downloads/
PHP Analyzer − to handle PHP script instructions must install a parser to generate HTML output that can be sent to a Web browser. This tutorial will guide you through how to install the PHP parser on your computer.
PHP Parser Installation
Before proceeding, make sure you have the right environment set up on your machine, and it is very important to use PHP to develop web programs. Save the following PHP file in the Apache Htdocs folder.
phpinfo.php
<?php
phpinfo ()
Enter the following address in the browser's address bar to view the output.
Http://127.0.0.1/phpinfo.php
If this shows a page with information about PHP installation, it means that PHP and the Web server are installed correctly. Otherwise, you must follow a specific program to install PHP on your computer.
This section will guide you through installing and configuring PHP on the following four platforms (this series is based on the WIN10 installation apache+php development environment)-
Linux/unix install apache+php environment
Mac OS x Install apache+ PHP Environment
Install apache+php environment on WINDOWS10
Apache configuration
If you use Apache as your Web server, this section will guide you through editing Apache's configuration file.
For more information, see here −apache server configuration php
php. INI file configuration
PHP configuration file –php.ini, which will affect the most direct way of PHP functionality.
Windows IIS Configuration
If you want to configure IIS on your Windows computer, you can refer to the IIS manual. The
php7– scalar type declaration
has a new function in PHP7, and the scalar type declaration has been introduced. There are two options for scalar type declarations:
Coercion – Mandatory is the default mode and does not need to be specified. The
strict-strict mode has a clear hint.
The following types of function parameters can be enforced in this way:
int
Float
BOOL
String
Interfaces
Array
Callable
Sample-Force mode <?php
//Coercive mode
function sum (int ... $ints)
{
return array_sum ($ints);
}
Print (SUM (2, ' 3 ', 4.1));
?>
The browser produces the following 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));
?>
The browser produces the following output-
Fatal error:uncaught typeerror:argument 2 passed to sum () must is of the type Integer, string given, ...
php7– return type declaration
There is a new feature in PHP7 that returns type declarations have been introduced. The return type declaration specifies the return value type of a function. The following types of return types can be declared:
Int
Float
bool
String
Interfaces
Array
Callable
Example – a valid return type
<?php
Declare (Strict_types=1);
function returnintvalue (int $value): int
{
return $value;
}
Print (Returnintvalue (5));
?>
The browser produces the following output-
5
Example – Invalid return type
<?php
Declare (Strict_types=1);
function returnintvalue (int $value): int
{
return $value + 1.0;
}
Print (Returnintvalue (5));
?>
This will produce the following browser output-
Fatal error:uncaught Typeerror:return value of Returnintvalue () must be of the type integer, float returned ...
Php7–null merge operator
PHP7 a new feature, the null merge operator (?? ) has been launched. It is used to replace ternary operations with the Isset () function function. Returns the second operand if there is a and is not a null null merge operator to return its first 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);
?>
This will produce the following output in the browser-
Not passed
Not passed
Not passed
PHP7 spacecraft operator
In PHP7, there is a new function-the spacecraft operator is introduced successively. It is used to compare two expressions. It returns -1,0 or 1, respectively, when the first expression is less than the second expression, equal to or greater than.
Example
<?php
Integer comparison
Print (1 <=> 1);p rint ("<br/>");
Print (1 <=> 2);p rint ("<br/>");
Print (2 <=> 1);p rint ("<br/>");
Print ("<br/>");
Float comparison
Print (1.5 <=> 1.5);p rint ("<br/>");
Print (1.5 <=> 2.5);p rint ("<br/>");
Print (2.5 <=> 1.5);p rint ("<br/>");
Print ("<br/>");
string comparison
Print ("A" <=> "a");p rint ("<br/>");
Print ("A" <=> "B");p rint ("<br/>");
Print ("B" <=> "a");p rint ("<br/>");
?>
This will produce the following output in the browser-
0
-1
1
0
-1
1
0
-1
1
php7– Constants Array
Array constants can now be defined using the Define () function. In PHP5.6, they can only be defined using the Const keyword.
Example
<?php
Define a array using define function
Define (' animals ', [
' Dog ',
' Cat ',
' Bird '
]);
Print (animals[1]);
?>
This will produce the following output in the browser-
Cat
php7– Anonymous Class
Anonymous classes can now be defined by using the new class. Anonymous classes can be used to replace the complete 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 I-Log message");
?>
This will produce the following output in the browser-
My I-Log message
Php7–closure::call ()
The Closure::call () method is added to the temporary binding (BindTo) object range, and it is easier to close and invoke it than to bind to the PHP5.6 performance faster.
Example –PHP7 Previous version
<?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 ());
?>
This will produce the following output in the browser-
1
Sample-php7+
<?php
Class A {
Private $x = 1;
}
PHP 7+ Code, Define
$value = function () {
return $this->x;
};
Print ($value->call (new A));
?>
This will produce the following output in the browser-
1
php7-Filtration Unserialize ()
PHP7 introduces the filter unserialize () function to provide better security when deserializing an untrusted data object. It protects against possible code injection, allowing developers to use the serialized whitelist class.
Example
<?php
Class MyClass1 {
Public $obj 1prop;
}
Class MyClass2 {
Public $obj 2prop;
}
$obj 1 = new MyClass1 ();
$obj 1->obj1prop = 1;
$obj 2 = new MyClass2 ();
$obj 2->obj2prop = 2;
$SERIALIZEDOBJ 1 = serialize ($obj 1);
$SERIALIZEDOBJ 2 = serialize ($obj 2);
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 ($serializedObj 1, ["Allowed_classes" => true]);
Converts all objects into __php_incomplete_class object except those of MyClass1 and MyClass2
$data 2 = unserialize ($serializedObj 2, ["Allowed_classes" => ["MyClass1", "MyClass2"]]);
Print ($data->obj1prop);
Print ("<br/>");
Print ($data 2->obj2prop);
?>
This will produce the following output in the browser-
1
2
php7– International character
In PHP7, the new Intlchar class is added for its purpose to expose more ICU functionality. This class defines a number of static methods and constants that can be used to manipulate Unicode characters. You need to install INTL extensions before using this class.
Example
<?php
printf ('%x ', Intlchar::codepoint_max);
Print (Intlchar::charname (' @ '));
Print (intlchar::ispunct ('! '));
?>
This will produce the following output in the browser-
10ffff
Commercial at
True
Php7–csprng
In PHP7, the following two new functions have been introduced to encrypt secure integers and strings in a cross-platform manner.
Random_bytes () – Generates cryptographic security pseudo-random bytes.
Random_int () – Generates a cryptographic secure pseudo-random integer.
Random_bytes ()
Random_bytes () is suitable for using to generate a password, random arbitrary length of a string, such as: Generate salt, key or initial vector.
Grammar
String random_bytes (int $length)
Parameters
length– returns the byte length of a random string
return value
Returns a string containing the number of requests for encrypted secure random bytes.
Error/exception
If the appropriate source of randomness cannot be found, an exception is thrown
If the given argument is invalid, TypeError will be thrown
If the byte length is given is invalid, the error is thrown
Example
<?php
$bytes = Random_bytes (5);
Print (Bin2Hex ($bytes));
?>
This will produce the following output in the browser-
54cc305593
Random_int ()
Random_int () produces cryptographic random integers that are appropriate for the result to be very important.
Grammar
int random_int (int $min, int $max)
Parameters
min– returns the minimum value, which must be a php_int_min or greater value
max– returns the maximum value, which must be less than or equal to Php_int_max
return value
Returns the minimum (min) to maximum (max) range, including cryptographic security random integers.
Error/exception
Throws an exception if an appropriate source of randomness cannot be found
If the given argument is invalid, TypeError will be thrown
If Max is less than min, the error is thrown
Example
<?php
Print (Random_int (100, 999));
Print ("
");
Print (Random_int (-1000, 0));
?>
This will produce the following output in the browser-
614
-882
php7– expectation
Expectations are backward-compatible enhancements to the old assert () function. Expect to allow assertions in production code 0 costs and provide the ability to throw custom exceptions when an assertion fails. ASSERT () is not a language builder, where the first argument is a comparison string of an expression or a Boolean for testing.
Configuration directive assert ()
Directive Default value
Possible values
Zend.assertions 1
Create and execute code (development mode)
0– generates code, but at run time
-1– does not generate code (production mode)
Assert.exception 0
The one that throws when an assertion fails, either throws an exception, or throws an object provided by throwing a new Assertionerror object, if no exception is supplied
0– used or generated with the above Throwable, but only based on the object's warning rather than (with PHP 5 compliant behavior) throw it
Parameters
assertion– assertion. In PHP 5, this must be to compute a string or to test a Boolean value. In PHP 7, this may also be a return value expression that will execute and use the result to indicate whether the assertion succeeds or fails.
description– an optional description that will include a failure message if the assertion fails.
exception-in PHP7, the second argument can be a Throwable object, not a description 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 value
True if the assertion is false.
Example
<?php
Ini_set (' assert.exception ', 1);
Class Customerror extends Assertionerror {}
ASSERT (False, new Customerror (' Custom Error message! '));
?>
This will produce the following output in the browser-
Fatal error:uncaught customerror:custom Error message! In .....
Php7–use statement
From PHP7, a single use statement can be used to import classes, functions, and constants from the same namespace (without using the USE statement more than once).
Example
<?php
Before PHP 7
Use Com\yiibai\classa;
Use COM\YIIBAI\CLASSB;
Use COM\YIIBAI\CLASSC as C;
Use function com\yiibai\fn_a;
Use function Com\yiibai\fn_b;
Use function Com\yiibai\fn_c;
Use const Com\yiibai\consta;
Use const COM\YIIBAI\CONSTB;
Use const COM\YIIBAI\CONSTC;
PHP 7+ Code
Use Com\yiibai\{classa, CLASSB, classc as C};
Use function com\yiibai\{fn_a, Fn_b, Fn_c};
Use const Com\yiibai\{consta, CONSTB, CONSTC};
?>
php7– Error Handling
From PHP7, error handling and reporting have changed. The traditional error reporting mechanism is used in PHP5, and most of the errors are now handled by throwing exception errors. Similar to exceptions, these error exceptions bubble until they reach the first matching catch block. If there is no matching block, then a default exception handling is installed using Set_exception_handler (), and, in the case, if there is no default exception handler, the exception is converted to a fatal error and treated like a traditional error.
Because the error hierarchy is not from an exception (Exception), Code extensions use catch (Exception $e) {...} blocks to handle an unhandled exception, which will not be handled in PHP5. A fatal error that a catch (Error $e) {...} block or Set_exception_handler () handler needs to handle.
Exception Hiearchy
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 ());
?>
The following output is generated in the browser-
Modulo by zero
php7– Integer Division
PHP7 introduces a new function of Intdiv () that performs integer division of operands and returns the result to type int.
Example
<?php
$value = Intdiv (10,3);
Var_dump ($value);
Print ("
");
Print ($value);
?>
This will produce the following output in the browser-
Int (3)
3
Php7–session Options
The Php7+,session_start () function accepts the array parameter overrides the session configuration Directive set in PHP.ini. These options support Session.lazy, which overwrites any session data information by default if the PHP session data changes.
Adding another option is: Read_and_close, which indicates that the session data should be read, and that the session should be immediately closed. For example, Session.cache_limiter is set to private and a flag is closed immediately after the following code fragment is used.
<?php
Session_Start ([
' Cache_limiter ' => ' private ',
' Read_and_close ' => true,
]);
?>
php7– deprecated features
The following features have been canceled and may be removed in future versions of PHP.
PHP4-style constructors
The PHP4 constructor, which is the same as the name of the class, because they are methods of the defined class, are now obsolete, and will be removed in the future. If PHP4 is constructed merely as a constructor in a class, PHP7 will emit e_deprecated. Class implementation Constructor __construct () method is not affected.
Example
<?php
Class A {
function A () {
Print (' Style constructor ');
}
}
?>
This will produce the following output in the browser-
Deprecated:methods with the same name as their class won't is constructors in a future version of PHP; A has a deprecated constructor in ...
static invocation of Non-static methods
Non-static method static calls have been deprecated and may be removed in the future.
Example
<?php
Class A {
Function B () {
Print (' non-static call ');
}
}
A::b ();
?>
This will produce the following output in the browser-
Deprecated:non-static method A::b () should is called statically in ...
Non-static Call
Password_hash () Salt option
The salt option for the Password_hash () function has been deprecated, so that developers do not produce their own (usually unsafe) salt. The function itself generates an encrypted security salt when the developer does not provide a salt value – Therefore, custom salt generation is no longer needed.
Capture_session_meta SSL Context Options
Capture_session_meta SSL Contextual selections have been deprecated. SSL metadata is now acquired through the Stream_get_meta_data () function.
PHP7 deleted extensions
The following extensions are removed from PHP7
Ereg
Mssql
Mysql
Sybase_ct
PHP7 deleted SAPI
The following sapi are removed from PHP7
Aolserver
Apache
Apache_hooks
Apache2filter
Caudium
Continuity
Isapi
Milter
Nsapi