0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP5とPHP8の違い

Posted at

① nullチェックの違い

オブジェクトが null でも安全にアクセスする。
ネストが深いほどPHP8の書き方が見やすくなる。
★php5

if($user && $user->profile && $user->profile->name){
 echo $user->profile->name;
}

★php8


echo $user?->profile?->name;

② switch → match式(新構文)

値に応じた条件分岐(戻り値あり・型も厳密)
match は === 比較(型も一致)& 戻り値として使える。

★php5

switch($status){
case 200 :echo 'OK'; 
break;
case 404 :echo 'Not found'; 
break;
default: echo 'unknown';
};

★php8

echo match($status){
    200 =>'OK',
    404 =>'Not Found',
    default =>'Unknown',
};

③ コンストラクタプロパティプロモーション

プロパティの定義と代入を一行で書けるようになった。
コードが簡潔で、冗長さが大幅に減る。
★php5

class User {
    public $name;
    public $age;
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

★php8

class User {
    public function __construct(public string $name, public int $age) {}
}

⑤ 複数型対応(Union型)

引数に複数の型を許容したい場合の対応
複雑なバリデーションが不要になった。

★php5

function test($val){
if(!is_int($val) &&!is_strig($val)){
throw new Exception('型が違う');
 }
}

★php8

function test(int|string $val){
//OK
}

⑥ 名前付き引数(Named Arguments)

PHP8では名前付き引数が導入され、引数を順番に依存せずに渡すことが可能になった。
★php5

function createUser($name,$age,$admin =false){}

createUser("Taro",30,true);

★php8

function createUser($name,$age,$admin =false){}

createUser(name:"Taro",age:30,admin:true);

⑦ throwが式として使える

throw を ?? や ?: の中で使えるかどうか
一行で処理が完結し、読みやすくなる。
★php5

if ($param === null) {
    throw new InvalidArgumentException("paramが必要");
}
$value = $param;

★php8

$value = $param ?? throw new InvalidArgumentException("paramが必要");

⑧ JIT(Just-in-Time)コンパイルの導入

実行時の処理速度向上

★php5
処理速度は遅め(とくにループや数値演算)
★php8
JITにより、特定処理で 最大2倍以上の高速化

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?