PHP7 New characteristics

Scalar type declaration

PHP Scalar type of :

  • bool
  • int
  • float
  • string
function addOne(int a) {
    return a + 1;
}


function addA(string a) {
    return a . "A";
}

Strict type declaration

<?php
declare(strict_types=1);

Return type declaration

<?php


class A {
    private $name;
    
    function __construct(string $name) {
        $this->name = $name;
    }
    
    /**
     * @return mixed
     */
    public function getName() {
        return $this->name;
    }
}


function getString(): string {
    return "";
}


function getArray(): array { 
    return [];
}


function getInt(): int {
    return 1.2;
}


function getInt2(): int {
    return '123';
}


function getInt3(): int {
    return '123a';
}


function createA(string $name): A {
    return new A($nam

Empty merge operator

The empty merge operator is represented by two question marks : ??, Used to check whether a value exists and is not empty , Then return the first operand , Otherwise, return the second operand .

$username = $_SERVER['username'] ?? 'not define';
echo $username . PHP_EOL;


$username = isset($_SERVER['username']) ? $_SERVER['username'] : 'not define';
echo $username . PHP_EOL;


$username = $_SERVER['username'] ?? getenv('USER') ?? 'not define';
echo $username . PHP_EOL;

The ship operator

You can use <=> Express , To compare two expressions , Returns when less than -1, When equal, return 0, If greater than, return 1

echo 1 <=> 2 . PHP_EOL; // 1
echo 1 <=> 1 . PHP_EOL; // 0
echo 5 <=> 3 . PHP_EOL; // -1

Use define Defining a constant array

<?php


define('NAME', ['A', 'B', 'C', 'D']);




// NAME[] = 'E';


print_r(NAME

Deconstruct assignment

Can be in list Function key.

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];


// list() style
list("id" => $id1, "name" => $name1) = $data[0];


// [] style
["id" => $id1, "name" => $name1] = $data[0];


// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
    // logic here with $id and $name
    echo "$name";
}


// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
    echo "$name";
    // logic here with $id and $nam

An anonymous class

When a class doesn't need to be recorded , Or an anonymous class can be considered when it is only used once in execution .

interface Writer {
    public function write(string $message);
}


function http_response(Writer $writer, $body, $headers=[], $version='HTTP/1.1') {
    $writer->write("$version 200 OK\r\n");
    $writer->write("Content-Type: text/html\r\n");
    $writer->write("Content-Length: " . strlen($body) . "\r\n");
    foreach ($headers as $header => $val) {
        $writer->write("$header: $val\r\n");
    }
    
    $writer->write("\r\n");
    $writer->write($body);
}


http_response(new class implements Writer {
    public function write(string $message) {
        echo $message;
    }
}, "something", array(
    'Location' => '/'
));

Namespace Group Import

  • Import multiple classes within the namespace :use App\Module\{Foo, Bar, Baz}
  • Import multiple functions within a namespace : use function App\Tool\{some_function}
  • Multiple constants falling into the namespace :use const App\Tool\{A};

Heredoc

PHP7Heredoc With a more flexible grammar , Improved readability .

  • Allow the end tag to zoom in
  • Delete the new line after the end tag
$templates = array(
    <<<EOF
    sdkf
    skldjfls
    sdfljkl
    sdf
    ksdjfl
    sdfl
    sdfjl
    EOF,
    <<<EOF
    xxxx
    yyyy
    zzzz 
    EOF
);

Class constant visibility

class Bar {
    public const A = 1;
    protected const B = 2;
    private const C = 3;
}

Supports negative string offset

$name = 'name';


echo $name[-1];
// output e


PHP5 Migrate to PHP7 What you need to pay attention to when writing code

Keep the interface compatible : Subclasses override superclasses / The method of realizing interface should pay attention to parameter compatibility

<?php


class P {
    public function printMessage($msg, $newline=false) {
        echo $newline ? $msg.PHP_EOL : $msg;
    }
}






class S extends P {
    #  FALSE 
    public function printMessage($msg, $newline) {
    }
}


class S extends P {
    #  Correct 
    public function printMessage($msg, $newline=false) {
        
    }
}




# output


Warning: Declaration of S::printMessage($msg, $newline)
should be compatible with P::printMessage($msg, $newline = false) 
in /root/phpnewfeatures/parent_sub_class_method.php on l

The reference passing parameter is a variable .

<?php


function group_by_key(&$arr, $key) {}
function new_array() {
  return [];
}


$arr = [];
group_by_key($arr, 'key'); #  Correct 




group_by_key([], 'key'); #  FALSE 
group_by_key(new_array(), 'key'); #  FALSE 




# output


PHP Fatal error:  Only variables can be passed by reference 
in /root/phpnewfeatures/array_parameter_ref.php on li

switch The structure of the continue Statement produces a warning , Should use the break.

<?php


for ($i = 0; $i < 3; $i++) {
  switch ($i) {
    case 1:
      continue;
    case 2:
      echo 'yes';
      break;
    default:
      break;
  }
}


# output


PHP Warning:  "continue" targeting switch is equivalent to "break".
Did you mean to use "continue 2"? 
in /root/phpnewfeatures/switch_case_no_continue.php on line

An exception is thrown when too few arguments are passed , When calling a user-defined function , If the parameters are too few , stay PHP7 A warning will be generated before , stay PHP7 It throws an exception .

<?php


function addInts($a, $b, $c) {
    return $a + $b + $c;
}




addInts(1,2, 3);
addInts(1,2);


# output php5
PHP Warning:  Missing argument 3 for addInts(), 
called in /root/phpnewfeatures/too_few_args.php on line 9 and 
defined in /root/phpnewfeatures/too_few_args.php on line 3


# output php7
PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function addInts(), 2 passed
in /root/phpnewfeatures/too_few_args.php on line 9 and 
exactly 3 expected in /root/phpnewfeatures/too_few_args.p

The following name cannot be used as a class 、 Interface and trait The name of

  1. void
  2. iterable
  3. bool
  4. int
  5. string
  6. NULL
  7. TRUE
  8. FALSE
  9. FLOAT

Invalid string math operation

<?php


'1b' + 2;




PHP Notice:  A non well formed numeric value encountered 
in /root/phpnewfeatures/non_well_formed_numeric_encountered.php on line

Computes non countable types (non-countable) A warning will be issued when it's done . Call... On a non countable type count()( or sizeof()) function , Will throw out a E_WARNING error .

<?php


count('');
count(null);
count(false);
count('hello');
count(1);
count(new StdClass);




# output


Warning: count(): Parameter must be an array or an object that implements Counta

object In previous versions, it was declared as a soft reserved word , Now it's forced to keep words , The name is not allowed in any class or interface .

PHP Fatal error:  Cannot use 'object' as class name as it is reserved

Strings without quotes

  1. A string without quotation marks is a non-existent global constant , Into their own string . stay PHP7 before , This behavior produces E_NOTICE, But now there will be E_WARNING. The next PHP In the main version , Will throw out Error abnormal .

 

<?php
$b = hello;


echo $b;


#output


PHP Warning:  Use of undefined constant hello - 
assumed 'hello' (this will throw an Error in a future version of PHP)


hello


array(
a =>

Reference return , A function that returns a reference , Don't return an expression , To return a variable .

<?php


$config = [];


function &getConfig() {
   $item = 1;
   return $config[0] =& $item; # line 7
}


function &getConfig2() {
   $item = 1;
   $config[0] = $item;


   return  $item;
}


$c1 =& getConfig();
$c2 =& getConfig2();


?>




PHP Notice:  Only variable references should be returned by reference 
in /root/phpnewfeatures/ref_return_value.php on line 7


PHP Stack trace:
PHP   1. {main}() /root/phpnewfeatures/ref_return_value.php:0
PHP   2. getConfig() /root/phpnewfeatures/ref_return_value.php:17


Notice: Only variable references should be returned by reference 
in /root/phpnewfeatures/ref_return_value.php on line 7


Call Stack:
    0.0011     391504   1. {main}() /root/phpnewfeatures/ref_return_value.php:0
    0.0011     391504   2. getConfig() /root/phpnewfeatures/ref_return_valu

json_decode When decoded as an object , If json If the key is empty, an empty property name will be created , instead of _empty__ As property name .

<?php


var_dump(json_decode('{"": 1}'));


#php7
class stdClass#1 (1) {
  public $ =>
  int(1)
}


#php5
class stdClass#1 (1) {
  public $_empty_ =>
  int(1)

json_decode, If JSON In words true,false,null Not lowercase , Returns the null, And set up json_last_error.

<?php


var_dump(json_decode('{"checked": False}', true));
var_dump(json_last_error());


# php 7


/root/phpnewfeatures/json_decode_uppercase_true.php:3:
NULL
/root/phpnewfeatures/json_decode_uppercase_true.php:4:
int(4)


# php 5


array(1) {
  'checked' =>
  bool(false)
}
int

Number string conversion follows the scientific counting method

  1. Include (int) The cast operation and the following functions
    1. intval
    2. settype
    3. decbin
    4. decoct
    5. dechex

 

<?php


echo (int) '123e3';


# php7
123000


# php5
1

Empty index operators are no longer supported for strings , stay PHP7 It will be converted to an array silently before .

<?php


$str = '';
$str[] = 'x';


# php5
array(1) {
  [0] =>
  string(1) "x"
}


# php7
PHP Fatal error:  Uncaught Error: [] operator not supported for strings 
in /root/phpnewfeatures/string_empty_index.php:5
Stack trace:
#0 {main}
  thrown in /root/phpnewfeatures/string_empty_index.php on line 5


Fatal error: Uncaught Error: [] operator not supported for strings 
in /root/phpnewfeatures/string_empty_index.php on line 5


Error: [] operator not supported for strings 
in /root/phpnewfeatures/string_empty_index.php on line 5


Call Stack:
    0.0007     391296   1. {main}() /root/phpnewfeatures/string_empty_index.ph

MCrypt Has expired ,mcrypt Library in 2007 I haven't seen any updates since , It is no longer recommended to use . have access to OpenSSL or Sodium replace .

list No longer able to unravel string

<?php


$str = 'abcdfg';


list($a, $b, $c) = $str;


var_dump($a, $b, $c);


# php5
string(1) "a"
string(1) "b"
string(1) "c"


# php7


/root/phpnewfeatures/list_string.php:7:
NULL
/root/phpnewfeatures/list_string.php:7:
NULL
/root/phpnewfeatures/list_string.php:7:

Hexadecimal strings are no longer considered numbers

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>


#php5


bool(true)
bool(true)
int(15)
string(2) "oo"


#php7
/root/phpnewfeatures/hexstring.php:3:
bool(false)
/root/phpnewfeatures/hexstring.php:4:
bool(false)
PHP Notice:  A non well formed numeric value encountered in /root/phpnewfeatures/hexstring.php on line 5
PHP Stack trace:
PHP   1. {main}() /root/phpnewfeatures/hexstring.php:0


Notice: A non well formed numeric value encountered in /root/phpnewfeatures/hexstring.php on line 5


Call Stack:
    0.0008     390712   1. {main}() /root/phpnewfeatures/hexstring.php:0


PHP Notice:  A non well formed numeric value encountered in /root/phpnewfeatures/hexstring.php on line 5
PHP Stack trace:
PHP   1. {main}() /root/phpnewfeatures/hexstring.php:0


Notice: A non well formed numeric value encountered in /root/phpnewfeatures/hexstring.php on line 5


Call Stack:
    0.0008     390712   1. {main}() /root/phpnewfeatures/hexstring.php:0


/root/phpnewfeatures/hexstring.php:5:
int(0)
PHP Notice:  A non well formed numeric value encountered in /root/phpnewfeatures/hexstring.php on line 6
PHP Stack trace:
PHP   1. {main}() /root/phpnewfeatures/hexstring.php:0
PHP   2. substr() /root/phpnewfeatures/hexstring.php:6


Notice: A non well formed numeric value encountered in /root/phpnewfeatures/hexstring.php on line 6


Call Stack:
    0.0008     390712   1. {main}() /root/phpnewfeatures/hexstring.php:0
    0.0049     390744   2. substr() /root/phpnewfeatures/hexstring.php:6


/root/phpnewfeatures/hexstring.php:6:
stri