【PHP】PHP8.4の概要

PHP

Laravel Newsの記事でも掲載されていましたが、

PHP8.4が2024年11月21日にリリース予定です。

A Look at What's Coming to PHP 8.4 - Laravel News
PHP 8.4 will be released on November 21, 2024 with property hooks, class instantiation method chaining without surroundi...

その半年前から、Alphaリリース、Betaリリース、リリース候補、が出される予定です。

予定の詳細はPHP公式のGitHubリポジトリに掲載されています。

policies/release-process.rst at main · php/policies
A collection of the policies and guidelines that set out PHP's development - php/policies
リリース名リリース日
Alpha 12024年7月4日(アメリカ独立記念日)
Alpha 22024年7月14日(フランス革命記念日)
Alpha 32024年7月28日(ペルー独立記念日)
Beta 12024年8月15日(インド独立記念日)
Beta 22024年8月29日(ポルトガルがブラジルの独立を承認した日)
Beta 32024年9月12日(エチオピア革命の日)
リリース候補 12024年9月26日(ニュージーランド事実上独立の日)
リリース候補 22024年10月10日(中華民国(台湾)国慶日)
リリース候補 32024年10月24日(ザンビア共和国独立記念日)
リリース候補 42024年11月7日(ロシア十月革命の日)

※なんだか意味深な日付ですが、筆者は共産主義者ではありません。

PHP Property Hooks

PHP8.4の大きな特徴の1つとして、「Property Hooks」があります。

Laravel Newsの記述を引用すると、

Property hooks are inspired by languages like Kotlin, C#, and Swift, and the syntax includes two syntax variants that resemble short and multi-line closures:

PHP Property Hooks | Laravel News

▼自動翻訳

プロパティ フックは Kotlin、C#、Swift などの言語からインスピレーションを得ており、構文には短いクロージャと複数行のクロージャに似た 2 つの構文バリアントが含まれています。

Laravel Newsのコードを引用すると、

class User implements Named
{
    private bool $isModified = false;
 
    public function __construct(
        private string $first,
        private string $last
    ) {}
 
    public string $fullName {
        // Override the "read" action with arbitrary logic.
        get => $this->first . " " . $this->last;
 
        // Override the "write" action with arbitrary logic.
        set {
            [$this->first, $this->last] = explode(' ', $value, 2);
            $this->isModified = true;
        }
    }
}

クラスプロパティの「$fullName」の宣言箇所で「get」「set」のクロージャ―が定義されています。

Laravel Newsの解説原文を引用すると、

Property hooks will help remove boilerplate of property getters and setters, allowing a property to define access and updates using hooks.

Check out our post for more details: Property Hooks in PHP 8.4.

▼自動翻訳

プロパティ フックは、プロパティのゲッターとセッターのボイラープレートを削除するのに役立ち、フックを使用してプロパティでアクセスと更新を定義できるようになります。

詳細については、「PHP 8.4 のプロパティ フック」の投稿をご覧ください。

ボイラープレートは「毎度おなじみの繰り返し行う決まりきった記述」のことです。

上記リンク先の詳細記事をさらに引用すると、

The syntax doesn’t require that both hooks always be defined together; in fact, here’s an example of only defining set from the RFC:

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

▼自動翻訳

構文では、両方のフックを常に一緒に定義する必要はありません。実際、RFC から set のみを定義した例を次に示します。

さらにコードも引用すると、

class User
{
    public string $name {
        set {
            if (strlen($value) === 0) {
                throw new ValueError("Name must be non-empty");
            }
            $this->name = $value;
        }
    }
 
    public function __construct(string $name) {
        $this->name = $name;
    }
}

このように「set」のみクロージャ―として定義されています。

「get」を必ずペアとして定義する必要は無いということです。

RFCの提言の詳細は

PHP: rfc:property-hooks

にありますが(非常に長い内容です)、このような記述も見受けられます。

class Foo
{
    public int $runs = 0 {
        set {
            if ($value <= 0) throw new Exception();
            $this->runs = $value;
        }
    }
}
 
$f = new Foo();
 
$f->runs++;

プロパティのデフォルト定義の後ろに波括弧でプロパティフックを記述しています。

また、実際のプロパティへのアクセスも記述されています。

これらのプロパティフックを利用することで、

かなりスッキリしたコードにすることができるようです。

new MyClass()->method() without parentheses

これは、インスタンス生成時に括弧を使わずにメソッドチェーンを使える機能です。

▼PHP8.3以前のコード

(new MyClass())->method()

▼PHP8.4のコード

new MyClass()->method()

Laravel Newsの内容を引用すると、

Since member access during instantiation was introduced, you must wrap the new MyClass() call in parentheses, or you’ll get a parse error. The proposed syntax would allow you to access constants, properties, and methods without the extra parentheses:

▼自動翻訳

インスタンス化中のメンバー アクセスが導入されたため、新しい MyClass() 呼び出しをかっこで囲む必要があります。そうしないと、解析エラーが発生します。提案された構文を使用すると、追加のかっこなしで定数、プロパティ、メソッドにアクセスできます。

これで少しスッキリしたコードになりますね。

Laravel Newsの内容を引用すると、

This update fixes papercut that makes working with class member access simpler, not having to add surrounding parentheses or using a static constructor method. This syntax change also puts PHP more in alignment with other C languages like Java, C#, and TypeScript, which don’t require surrounded parentheses.

▼自動翻訳

この更新によりペーパーカットが修正され、クラス メンバー アクセスの操作がより簡単になり、括弧を追加したり、静的コンストラクター メソッドを使用したりする必要がなくなりました。この構文の変更により、PHP は、括弧で囲む必要のない Java、C#、TypeScript などの他の C 言語とより整合性が高くなります。

これまた、Laravel Newsの別記事に詳細があります。

Is class instantiation without extra parenthesis coming to PHP 8.4? - Laravel News
Will we be able to drop parenthesis around the new keyword when instantiating a class? Find out the latest on the status...

この詳細記事のコードを引用すると、このようなアクセスもできるようです。

var_dump(
    new MyClass()::CONSTANT,        // string(8)  "constant"
    new MyClass()::$staticProperty, // string(14) "staticProperty"
    new MyClass()::staticMethod(),  // string(12) "staticMethod"
    new MyClass()->property,        // string(8)  "property"
    new MyClass()->method(),        // string(6)  "method"
    new MyClass()(),                // string(8)  "__invoke"
);

RFCの詳細は次の記事にあります。「プロパティフック」よりは短い内容です。

PHP: rfc:new_without_parentheses

RFC全体の内容は次の記事にあります。

PHP: rfc

とりあえず、7月4日のAlphaリリースを待つことにしましょう。

新しく提案された配列検索関数については次の記事をご覧ください。

コメント

タイトルとURLをコピーしました