これは個人的には一番待ち望んでた機能。
これでGetterをわざわざ作らずに済むので非常に簡潔に書ける。
特にプロパティの数が増えると煩雑さがだいぶ緩和される印象。
class Color{
public readonly int $r;
public readonly int $g;
public readonly int $b;
public readonly int $a;
public function __construct($r,$g,$b,$a){
$this->r = $r;
$this->g = $g;
$this->b = $b;
$this->a = $a;
}
}
ただしreadonly属性をつけるときはプロパティに型を指定しないとエラーになる。
public readonly $r;// Fatal error: Readonly property Color::$r must have type
ちなみにreadonlyを使わないで書くとこうなる。
class ColorClassic{
private int $r;
private int $g;
private int $b;
private int $a;
public function getR():int{
return $this->r;
}
public function getG():int{
return $this->g;
}
public function getB():int{
return $this->b;
}
public function getA():int{
return $this->a;
}
public function __construct($r,$g,$b,$a){
$this->r = $r;
$this->g = $g;
$this->b = $b;
$this->a = $a;
}
}