In this article, we will take 15 minutes to briefly review the changes to the PHP V7.x version. With the release of PHP 7.3, I decided to take a closer look at PHP development: what’s being developed and where it’s heading in order to better understand the new features and optimizations of this widely popular programming language.

10 years of architects share advanced PHP architecture information to help everyone achieve 30K

zhuanlan.zhihu.com] (zhuanlan.zhihu.com/p/340304217)

After reviewing a brief list of features PHP implemented during the development of PHP 7.x, I decided to put together this list myself as a nice addition that I’m sure some people will find useful. We’ll start with PHP 5.6 as a baseline and explore what was added or changed. I’ve also added a direct link to the official documentation for each feature mentioned, so if you’re interested in reading more, feel free to.

PHP 7.0

Support for anonymous classes There are two situations in which anonymous classes may be used in named classes:

  • When the class is not necessarily recorded

  • When the class is used only once during program execution

    New class(I) {public function __construct(I) {this−> I =this-> I =this −> I = I; }}

Divisible function – Safe division (even if divisible by 0) This function returns the integer portion of the result after the first argument is divisible by the second argument. When the divisor (the second argument) is 0, the function throws an E_WARNING error and returns FALSE.

intdiv(int $numerator, int $divisor)
Copy the code

Added new null merge operation assignment — i.e. “??”

$x = NULL; $y = NULL; $z = 3; var_dump($x ?? $y ?? $z); 
// int(3)  $x = ["c" => "meaningful_value"]; 
var_dump($x["a"] ?? $x["b"] ?? $x["c"]); // string(16) "meaningful_value"
Copy the code

Add new operator – spaceship (<=>)

The shuttle symbol is used to optimize and simplify comparison operations.

Function order_func($a, $b) {return ($a < $b)? -1 : (($a > $b) ? 1:0); Function order_func($a, $b) {return $a <=> $b; }Copy the code

Scalar type declaration

This is just the first step towards implementing more strongly typed programming language features in PHP-V0.5.

function add(float $a, float $b): float {     return $a + $b; }  add(1, 2); // float(3)
Copy the code

Return type declaration

Added the ability to return types other than scalar classes, including inheritance. Somehow it was not set as an optional feature (explained in V7.1)

interface A { static function make(): A; } class B implements A { static function make(): A { return new B(); }}Copy the code

Group usage statement

// Explicit syntax: use FooLibrary\Bar\Baz\ClassA; use FooLibrary\Bar\Baz\ClassB; use FooLibrary\Bar\Baz\ClassC; use FooLibrary\Bar\Baz\ClassD as Fizbo; Use FooLibrary\Bar\Baz\{ClassA, ClassB, ClassC, ClassD as Fizbo};Copy the code

Generator delegate generator function body allows the following new syntax:

yield from <expr>
Copy the code

Performance improvements PHP 7 is twice as fast as PHP 5.6.

Significantly reduce memory footprint

As you can see from the chart, PHP 7.0 has significant improvements in performance and (reduced) memory footprint. For pages with database queries, version 7.0.0 is 3 times faster with OpCache enabled and 2.7 times faster without OpCache enabled than version 5.6. In terms of memory occupancy, the difference between the two is also very obvious. The Throwable interface ** ** refactored exception classes have a non-intuitive naming scheme and can reduce confusion, especially for beginners.

Errors and Exceptions now implement Throwable.

This is the Throwable hierarchy:

interface Throwable |- Error implements Throwable |- ArithmeticError extends Error |- DivisionByZeroError extends ArithmeticError |- AssertionError extends Error |- ParseError extends Error |- TypeError extends Error |- ArgumentCountError extends TypeError |- Exception implements Throwable |- ClosedGeneratorException extends Exception |- DOMException extends Exception |- ErrorException extends Exception |- IntlException extends Exception |- LogicException extends Exception |- BadFunctionCallException extends LogicException |- BadMethodCallException extends BadFunctionCallException |- DomainException extends LogicException |- InvalidArgumentException extends LogicException |-  LengthException extends LogicException |- OutOfRangeException extends LogicException |- PharException extends Exception  |- ReflectionException extends Exception |- RuntimeException extends Exception |- OutOfBoundsException extends RuntimeException |- OverflowException extends RuntimeException |- PDOException extends RuntimeException |- RangeException extends RuntimeException |- UnderflowException extends RuntimeException |- UnexpectedValueException extends RuntimeExceptionCopy the code

⚠ warning! You can only implement Throwable by inheriting Error and Exception, which means that an interface inherited from Throwable can only be implemented by a subclass of Exception or Error. Unicode Codepoint escape syntax ** — “\u{XXXXX}” **

echo "\u{202E}Reversed text"; Echo "manana "; / / "ma \ u} {00 f1 ana" echo "manana"; // "man\u{0303}ana" "n"Copy the code

Context sensitive parser

* Globally reserved words become * semi-reserved:

callable  class  trait  extends  implements  static  abstract  final  public  protected  private  const
enddeclare  endfor  endforeach  endif  endwhile  and  global  goto  instanceof  insteadof  interface
namespace  new  or  xor  try  use  var  exit  list  clone  include  include_once  throw  array
print  echo  require  require_once  return  else  elseif  default  break  continue  switch  yield
function  if  endswitch  finally  for  foreach  declare  case  do  while  as  catch  die  self parent
Copy the code

Except that defining a class constant named class is still prohibited, because the class name resolves ::class. Generator return expression

Uniform variable syntax

Level support for the dirname () function

PHP 7.1

Nullable types

function answer(): ? int { return null; } function answer():? int { return 42; } function answer():? int { return new stdclass(); // error } function say(? string $msg) { if ($msg) { echo $msg; } } say('hello'); // success -- print hello say(null); // success -- do not print say(); // error -- argument missing say(new stdclass); // error -- error typeCopy the code

Void return

function should_return_nothing(): void { return 1; // Fatal error: void function cannot return value}Copy the code

Unlike other return types that are enforced when a function is called, this type is checked at compile time, which means that errors can occur when the function is not called.

Functions that have a void return type or a void function can either implicitly return or use a return statement without a value:

function lacks_return(): void {     // valid }
Copy the code

Iterable pseudo-type functions usually take or return an array or implement a Traversable object for use with foreach. However, because array is a basic type and Traversable is an interface, there is currently no way to use a type declaration on a parameter or return type to indicate that the value is iterable.

function foo(iterable $iterable) { foreach ($iterable as $value) { // ... }}Copy the code

Iterable can also be used as a return type, indicating that the function will return an iterable value. TypeError is raised if the value returned is not an array or instance of the Traversable.

function bar(): iterable {
    return [1, 2, 3];
}
Copy the code

Arguments declared as iterable can use null or arrays as default values.

function foo(iterable $iterable = [])
 {     // ... 
}
Copy the code

Callable closure

class Closure {... public static function fromCallable (callable $callable) : Closure {... }... }Copy the code

Square bracket syntax for array structure assignment

$array = [1, 2, 3]; $a, $b, $c] = $array; $a, $b, $c; / / use "a", "b" and "c" key respectively $a, $b, $c allocated $array elements in an array of values (" a "= > $a," b "= > $b," c "= > $c] = $array;Copy the code

Square bracket syntax for list()

$powersOfTwo = [1 => 2, 2 => 4, 3 => 8];
list(1 => $oneBit, 2 => $twoBit, 3 => $threeBit) = $powersOfTwo;
Copy the code

Visibility of class constants

Class Token {// Const const PUBLIC_CONST = 0; // Constants can also define visibility private const PRIVATE_CONST = 0; protected const PROTECTED_CONST = 0; public const PUBLIC_CONST_TWO = 0; Private const FOO = 1, BAR = 2; }Copy the code

Catch multiple exception types

Try {// part of the code... } the catch (ExceptionType1 | ExceptionType2 $e) {/ / Exception handling code} the catch (\ Exception $e) {/ /... }Copy the code

PHP 7.2

Parameter type enlargement

<? php class ArrayClass { public function foo(array $foo) { /* ... */}} // This RFC proposal allows types to be expanded to untyped, i.e., any type. // Types can be passed as arguments. // Any type of restriction can be implemented by user-written code in the method body. class EverythingClass extends ArrayClass { public function foo($foo) { /* ... * /}}Copy the code

Count () returns 1 when a scalar or object that does not implement Countable calls the count() method (illogical).

In PHP version 7.2, a WARNING was added to call count() as a scalar, null, or an object that does not implement the Countable interface.

Use trailing commas in list uses of namespaces

use Foo\Bar\{ Foo, Bar, Baz, };
Copy the code

Argon2 password hashing algorithm

The existing password function provides a simple forward-compatible interface for hashing passwords. This RFC proposes that the password function implement Argon2i (V1.3), which replaces the Bcrypt password hash algorithm.

Debug PDO preprocessing statement emulation

$db = new PDO(...) ; $STMT = $db->query('SELECT 1'); var_dump($stmt->activeQueryString()); // => string(8) "SELECT 1" $stmt = $db->prepare('SELECT :string'); $stmt->bindValue(':string', 'foo'); Var_dump ($STMT ->activeQueryString()); $STMT ->execute(); $STMT ->execute(); var_dump($stmt->activeQueryString()); // => string(11) "SELECT 'foo'"Copy the code

PHP 7.3

** JSON_THROW_ON_ERROR ** There has been no adequate way to handle errors with JSON for a long time, and developers around the world have identified this as a huge weakness of the language. Prior to PHP V7.2, we needed a way to get errors from JSON that was neither reliable nor proficient;

Examples are as follows:

json_decode("{"); Json_last_error () === JSON_ERROR_NONE json_last_error_msg()Copy the code

So let’s see how to use this new syntactic sugar:

use JsonException;

try {
    $json = json_encode("{", JSON_THROW_ON_ERROR);
    return base64_encode($json);
} catch (JsonException $e) {
    throw new EncryptException('Could not encrypt the data.', 0, $e);
}
Copy the code

As you can see from the above code, the jSON_encode function now has an optional parameter JSON_THROW_ON_ERROR – this will catch errors and display them with the following exception methods:

$e->getMessage(); Json_last_error_msg () $e->getCode(); Json_last_error ()Copy the code

Add the is_countable function

/ / before: If (is_array ($foo) | | $foo instanceof Countable) {/ / $foo is Countable} / / after the if (is_countable ($foo)) {/ / $foo is countable }Copy the code

Add array functions array_key_first(), array_key_last()

$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
Copy the code

Native support for same-site Cookie judgment There are two ways to use same-site Cookie judgment: Lax and Strict. They differ in the accessibility of cookies in cross-domain HTTP GET requests. Cookies using Lax allow cross-domain GET access, while cookies using Strict do not. The POST method makes no difference: the browser does not allow access to cookies in cross-domain POST requests.

Set-Cookie: key=value; path=/; domain=example.org; HttpOnly; SameSite=Lax|Strict
Copy the code

Migration from PCRE to PCRE2 Argon2 Hash password enhancements The existing password_* function provides a forward-compatible simplified interface for hashing passwords. This RFC suggests implementing Argon2id in the password _* function as a security alternative to the original proposed Argon2i. Trailing commas are allowed in function calls

$newArray = array_merge($arrayOne, $arrayTwo, ['foo', 'bar']);Copy the code

List () uses references

$array = [1, 2];
list($a, &$b) = $array;
Copy the code

Is equivalent to:

$array = [1, 2];
$a = $array[0];
$b = &$array[1];
Copy the code

Use of case-insensitive constants is not recommended

PHP 7.4 (in development)

Typed Properties parameter Type

class User { public int $id; public string $name; public function __construct(int $id, string $name) { $this->id = $id; $this->name = $name; }}Copy the code

Foreign Function Interface

The external function interface (FFI) is one of the most useful features of Python and LuaJIT for rapid prototyping. FFI enables pure scripting languages to call C functions and data types directly, making “system code” development more efficient. In FFI, PHP opens up a way to write PHP extensions in the PHP language and bind them to the C library.

(Null Coalescing Assignment Operator)

/ / a few lines of code below to complete the same function $this - > request - > data [' comments'] [' user_id '] = $this - > request - > data [' comments'] [' user_id ']?? 'value'; $this->request->data['comments']['user_id']?? = 'value';Copy the code

Preloading

PHP has used opcode caches for a long time (APC, Turck MMCache, Zend OpCache). They achieve significant performance gains by almost completely eliminating the overhead of recompiling PHP code. The new preloading capability will be implemented with a new php.ini configuration — opcache.preload. This configuration specifies a PHP file that will perform the preload task and then preload the other files either by including them or using the opcache_compile_file() function.

Always available Hash extension

This will make the hash extension (ext/hash) always available, similar to Date. The Hash extension provides a wealth of utility and hash algorithms that are not only good for PHP developers, but also for PHP itself.

On a trip to PHP 8.0

JIT.

In a nutshell. When you start a PHP program, Zend Engine parses the code into an abstract syntax tree (AST) and converts it into opcodes. The opcode is the execution unit of the Zend VM (Zend VM). The opcodes are fairly low-leve and can be converted to machine code much faster than raw PHP code.

PHP has an extension in the core called OPcache for caching these opcodes.

“JIT” is a technique for compiling parts of code at run time, so a compiled version can be used.

This is one of the newest and largest PHP optimization strategies still being discussed. PHP engineers are waiting to see how much performance this new feature can squeeze into their applications. I’m really keen to see this for myself. Consistent type errors for internal functions If parameter resolution fails, causes the internal parameter resolution API to always generate TypeError errors. It should be noted that these errors also include ArgumentCountError (a subclass of TypeError) for situations where too few/too many arguments are passed.

Performance comparison

I wrote a simple test to help you easily compare the performance of different VERSIONS of PHP (using Docker). This even makes it easy to check the performance of the new PHP version by adding a new container name. Running on a Macbook Pro, 2.5ghz Intel Core I7.

PHP version: 5.6.40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- test_math: 1.101 SEC. Test_stringmanipulation: Test_ifelse: 1.122 SEC. Mem: 429.4609375 KB Peak Mem: 1.144 sec. test_loops: 1.736 sec. test_ifelse: 1.122 SEC. 687.65625 KB -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Total time: : PHP version 5.103: 7.0.33 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- test_math: 0.344 SEC. Test_stringmanipulation: 0.516 SEC. Test_loops: 0.477 sec. test_ifElse: 0.373 sec. Mem: 421.0859375 KB Peak Mem: 422.2109375 KB -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Total time: : PHP version 1.71: 7.1.28 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- test_math: 0.389 SEC. Test_stringmanipulation: 0.514 SEC. Test_loops: 0.501 sec. test_ifelse: 0.464 sec. Mem: 420.9375 KB Peak Mem: 421.3828125 KB -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Total time: : PHP version 1.868: 7.2.17 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- test_math: 0.264 SEC. Test_stringmanipulation: 0.391 SEC. Test_loops: 0.182 sec. test_ifelse: 0.252 sec. Mem: 456.578125 KB Peak Mem: 457.0234375 KB -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Total time: : PHP version 1.089: Sections 7.3.4 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- test_math: 0.233 SEC. Test_stringmanipulation: 0.317 SEC. Test_loops: 0.171 sec. test_ifelse: 0.263 sec. Mem: 459.953125 KB Peak Mem: 460.3984375 KB -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Total time: : PHP version 0.984: 7.4.0 - dev -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- test_math: 0.212 SEC. Test_stringmanipulation: Test_ifelse: 0.228 SEC. Mem: 459.66406kb Peak Mem: 460.109375 KB -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Total time: : 1.003 if you are interested in your test, you can find the code in the warehouse meskis/PHP - bench.Copy the code

Eg. I love visual performance compilation of all major versions 5.6 and above on Servebolt.com – Eg. Fast Hosting. See the table below for the results. PHP 7.0.0 is an important milestone that significantly improves performance and reduces memory usage, but PHP maintainers can’t do much to improve it. The only remaining point is JIT (Just in time) compilation. It is part of PHP 8.0. Throughout the PHP 7.x release, there is a visible path to more typed (and more objective) and modern programming languages. Despite this, PHP likes to adopt concise and useful features found in other programming languages. We’ll see some better features soon, such as:

  • Named parameters
  • Nullsafe call
  • Enumerated types (ENUMs)
  • Arrow function

With this, PHP developers will join the ranks of modern programming language adopters. No language is perfect, but PHP paved the way for its future. To keep things short, I’ve listed the relatively important changes based on the latest version of PHP, 7.3. They are:

  • Added a new null merge operator
  • Scalar type declaration
  • Return type declaration
  • Throwable interface
  • Can be null
  • Empty return
  • Square bracket syntax for array destructor
  • Class constant visibility

Reference wiki.php.net/rfc www.cloudways.com/blog/php-5-… . WordPress 5.0 PHP 7.2 vs PHP 7.3 Performance and Speed Benchmark Interview questions for big companies

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

zhuanlan.zhihu.com] (Zhuanlan.zhihu.com/p/340637391…

zhuanlan.zhihu.com] (Zhuanlan.zhihu.com/p/340296144…

zhuanlan.zhihu.com] (Zhuanlan.zhihu.com/p/341488974…Redis these points, the interviewer must think you are very NB

zhuanlan.zhihu.com] (zhuanlan.zhihu.com/p/341722883)

Like my article to follow me, continue to update….. I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell script, Docker, micro services, Nginx and many other knowledge points can be shared free of charge to everyone, you can add the need to click here password: Autolink: EVOLUTION of PHP – from V5.6 to V8.0