ホームページ  >  記事  >  バックエンド開発  >  php7 の新機能の理解と比較について話しましょう

php7 の新機能の理解と比較について話しましょう

coldplay.xixi
coldplay.xixi転載
2020-06-20 17:32:412421ブラウズ

php7 の新機能の理解と比較について話しましょう

null 合体演算子 (??)

?? 構文: 変数が存在し、値が NULL でない場合は、独自の値を返します。それ以外の場合は、変数が返されます。 return it 2 番目のオペランド。

//php7以前  if判断if(empty($_GET['param'])) {
      $param = 1;
}else{
    $param = $_GET['param'];
}//php7以前  三元运算符$param = empty($_GET['param']) ? 1 : $_GET['param'];//PHP7  null合并运算符$param = $_GET['param'] ?? 1;//1

define() は定数配列を定義します

//php7以前define("CONTENT", "hello world");echo CONTENT;//hello world//PHP7define('ANIMALS', [    'dog',    'cat',    'bird']);echo ANIMALS[2];//bird//PHP7 类外也可使用const来定义常量const CONSTANT = 'Hello World'; 
echo CONSTANT;//Hello World

結合比較演算子 (96b4fef55684b9312718d5de63fb7121)

結合比較演算子は比較に使用されます。 2 つの式。a が b より小さい、等しい、または大きい場合、それぞれ -1、0、または 1 を返します。比較の原則は、PHP の一般的な比較規則に従うことです。

//整数echo 1 <=> 1; // 0echo 1 <=> 2; // -1echo 2 <=> 1; // 1//浮点数echo 1.5 <=> 1.5; // 0echo 1.5 <=> 2.5; // -1echo 2.5 <=> 1.5; // 1
 //字符串echo "a" <=> "a"; // 0echo "a" <=> "b"; // -1echo "b" <=> "a"; // 1

変数型宣言

2 つのモード: 必須モード (デフォルト) と厳密モード。次の型パラメーターを使用できます: string、int、float、bool

//... 操作符: 表示这是一个可变参数. php5.6及以上的版本可使用: 函数定义的时候变量前使用.function intSum(int ...$ints){    return array_sum($ints);
}
var_dump(intSum(2,&#39;3.5&#39;));//5//严格模式//模式声明:declare(strict_types=1);  默认情况值为0,值为1代表为严格校验的模式 declare(strict_types=1);function add(int $a,int $b){    return $a+$b;
}
var_dump(add(2,&#39;3.5&#39;)); //Fatal error: Uncaught TypeError: Argument 2 passed to add() must be of the type integer

戻り値の型宣言

戻り値の型宣言のサポートを追加します。パラメーターの型宣言と同様です。(使用方法については、関数定義の後に型名を追加します)

1 //有效的返回类型2 declare(strict_types = 1);3 function getInt(int $value): int {4   return $value;5 }6 print(getInt(6));//6
1 //无效返回类型2 declare(strict_types = 1);3 function getNoInt(int $value): int {4   return $value+&#39;2.5&#39;;5 }6 print(getNoInt(6));//Fatal error: Uncaught TypeError: Return value of getNoInt() must be of the type integer

匿名クラス

新しいクラス {} で匿名クラスを作成できるようにします。 object.

<?php//php7以前 接口实现interface User{    public function getDiscount();
}class VipUser implements User{    //折扣系数
    private $discount = 0.6;    public function getDiscount() {        return $this->discount;
    }
}class Goods{    private $price = 200;    private $objectVipUser;    //User接口VipUser类实现
    public function getUserData(User $User){        $this->objectVipUser = $User;
        $discount = $this->objectVipUser->getDiscount();        echo "商品价格:".$this->price*$discount;
    }
}
$display = new Goods();//常规实例化接口实现对象$display->getUserData(new VipUser);//商品价格:120
<?php//php7 创建一个匿名的对象interface User{    public function getDiscount();
}class Goods{    private $price = 200;    private $objectVipUser;    public function getUserData($User){        $this->objectVipUser = $User;
        $discount = $this->objectVipUser->getDiscount();        echo "商品价格:".$this->price*$discount;
    }
}
$display = new Goods();//new匿名对象实现user接口$display->getUserData(new class implements User{    private $discount = 0.6;    public function getDiscount() {        return $this->discount;
    }
});//商品价格:120

Closure::call()

Closure::call() メソッドは、オブジェクト スコープを一時的にクロージャにバインドして呼び出す簡単な方法として追加されました。 PHP5 の bindingTo 。そのパフォーマンスははるかに高速です。

<?php//php7以前class A {    private  $attribute = &#39;hello world&#39;;
}

$getClosure = function(){    return $this->attribute;
};

$getAttribute = $getClosure->bindTo(new A, &#39;A&#39;);//中间层闭包echo $getAttribute();//hello world
<?php//PHP7class A {    private  $attribute = &#39;hello world&#39;;
}

$getClosure = function(){    return $this->attribute;
};echo $getClosure->call(new A);//hello world

unserialize()

unserialize() 関数: フィルタリング機能により、不正なデータがコードに挿入されるのを防ぎ、より安全な逆シリアル化データを提供します。

<?php class A{  
   public $name = &#39;admin_a&#39;;    
} 
class B{ 
   public $name = &#39;admin_b&#39;; 
} 

$objA = new A(); 
$objB = new B(); 

$serializedObjA = serialize($objA); 
$serializedObjB = serialize($objB); 


//默认行为是接收所有类; 第二个参数可以忽略$dataA = unserialize($serializedObjA , ["allowed_classes" => true]); 
var_dump($dataA);//object(A)#3 (1) { ["name"]=> string(7) "admin_a" }//如果allowed_classes设置为false,unserialize会将所有对象转换为__PHP_Incomplete_Class对象 $dataA = unserialize($serializedObjA , ["allowed_classes" => false]); 
var_dump($dataA);//object(__PHP_Incomplete_Class)#4 (2) { ["__PHP_Incomplete_Class_Name"]=> string(1) "A" ["name"]=> string(7) "admin_a" }//转换所有对象到 __PHP_Incomplete_Class对象,除了对象"B"$dataB = unserialize($serializedObjB , ["allowed_classes" => ["B"]]); 
var_dump($dataB);//object(B)#3 (1) { ["name"]=> string(7) "admin_b" }

IntlChar

IntlChar: Unicode 文字情報にアクセスするために使用できるいくつかのユーティリティ メソッドへのアクセスを提供します。 注: 使用するには、Intl 拡張機能をインストールする必要があります!

1 var_dump(IntlChar::CODEPOINT_MAX);//int(1114111) 2 echo &#39;<br>&#39;;3 var_dump(IntlChar::charName(&#39;+&#39;));//string(9) "PLUS SIGN" 4 echo &#39;<br>&#39;;5 var_dump(IntlChar::ispunct(&#39;?&#39;));//bool(true)

CSPRNG

CSPRNG 関数は、暗号化乱数を生成する簡単なメカニズムを提供します。

random_bytes() - 暗号化で保護された擬似乱数文字列。

random_int() - 暗号化で保護された擬似乱数整数.

1 $bytes = random_bytes(8); 
2 echo(bin2hex($bytes));//随机2073a110a2e3c4973 echo &#39;<br>&#39;;4 echo(random_int(1, 999));//随机7865 echo &#39;<br>&#39;;6 print(random_int(-999, -1));//随机-357

use ステートメント

複数の use ステートメントを使用する代わりに、単一の use ステートメントを使用して、同じ名前空間からクラス、関数、および定数をインポートできます。

//PHP7之前use some\namespace\ClassA;use some\namespace\ClassB;use some\namespace\ClassC as C;use function some\namespace\fn_a;use function some\namespace\fn_b;use function some\namespace\fn_c;use const some\namespace\ConstA;use const some\namespace\ConstB;use const some\namespace\ConstC;// PHP7之后use some\namespace\{ClassA, ClassB, ClassC as C};use function some\namespace\{fn_a, fn_b, fn_c};use const some\namespace\{ConstA, ConstB, ConstC};

intp

新しく追加された intp() 関数は 2 つのパラメータを受け取り、戻り値は最初のパラメータの値を 2 番目のパラメータで割って四捨五入した値になります。

1 echo intp(8,4);//22 echo intp(10,4);//23 echo intp(5,10);//0

PHP7 エラー処理

PHP7 では、ほとんどのエラーが報告される方法が変更されました。PHP5 の従来のエラー報告メカニズムとは異なり、ほとんどのエラーはエラー例外としてスローされるようになりました。

This エラー例外は try/ によってキャッチできます。通常の例外と同様に catch ブロックを使用します。一致する try/catch ブロックがない場合は、例外処理関数 (set_Exception_handler() で登録) が呼び出されて処理されます。
例外処理関数が登録されていない場合は、例外処理関数で処理されます。従来の方法: 致命的なエラーとして報告されます (Fatal Error)
Error クラスは Exception クラスから拡張されていないため、catch (Exception $e) { ... } のようなコードはキャッチできません。エラー。catch (Error $e) { ... },
のようなコードを使用することも、例外処理関数 (set_Exception_handler()) を登録することで catch Error を使用することもできます。 ##

<?php//php7以前 自定义异常处理class getException extends Exception{    public function errorMsg(){        return &#39;错误的信息&#39;.$this->getMessage().&#39;<br>错误的代码&#39;.$this->getCode();
    }
}try {
    $num =10;    if($num > 1) {        throw new getException($num,404);
    }
} catch (getException $e) {    echo $e->errorMsg();
}
rrree
推奨チュートリアル: 「
PHP チュートリアル

以上がphp7 の新機能の理解と比較について話しましょうの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はliqingbo.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。