LoginSignup
32
15

More than 3 years have passed since last update.

PHP 7.4: 基底クラスのプロパティに型が無いと、継承クラスでは型が付けられない

Posted at

PHP 7.4 から登場する Typed properties(クラスのプロパティに型が付けられる機能)ですが、基底クラスのプロパティに型が無いと、継承クラスでは型が付けられません。(private は除く)
https://wiki.php.net/rfc/typed_properties_v2

例えば、下記のようなコードを実行すると、Fatal error: Type of Bar::$a must not be defined (as in class Foo) が発生します。

<?php
class Foo
{
    public $a;
}

class Bar extends Foo
{
    // これは NG
    public string $a;
}

これが問題になりそうなのが、フレームワークのように 7.4 未満を対象としたコードを継承する場合です。例えば、Laravel では、Eloquent を利用する際に継承するのですが、基底クラスにあるプロパティに関しては型が付けられません。

例えば、下記では、$table プロパティに string を付けているのですが、基底クラスの $table には型が付いていないので、PHP Fatal error: Type of App\Eloquents\EloquentCustomer::$table must not be defined が発生します。

<?php
declare(strict_types=1);

use Illuminate\Database\Eloquent\Model;

class EloquentCustomerPoint extends Model
{
    // これは NG
    protected string $table = 'customer_points';
    // これなら OK
    protected $table = 'customer_points';

7.4 に上げたからといって、全てのプロパティに型が付けられるわけではないのでご注意を。

32
15
1

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
32
15