20. PHP 8.0 改善/変更のポイント
20
<?php
class Test {
public int|float $x;
public function getVal() : int|float {
return $this->x;
}
}
$obj = new Test();
$obj->x = "1.23";
echo $obj->getVal(); // 1.23
Union: 引数,戻り値の型の候補を複数指定できる
RFC: https://wiki.php.net/rfc/union_types_v2
float(1.23)
21. PHP 8.0 改善/変更のポイント
21
属性(attribute): Java(annotation),Rust, Python (decorators)に類似
ユースケース:メタデータの記述,フレームワークにおけるルーティング,JITオプションなど
<?php
#[ClassAttribute(PHP_VERSION_ID)]
class Foo
{
#[PropertyAttribute(2+3*2)]
public $x;
#[Deprecated("Use bar()"),Jit(1255)]
public function moo() {}
}
RFC: https://wiki.php.net/rfc/attributes_v2
$ref = new ReflectionClass(Foo::class);
$attr = $ref->getProperty('x')->getAttributes();
$attr = $ref->getMethod('moo')->getAttributes();
$attr = $ref->getAttributes();
$attr[0]->getName(), $attr[0]->getArguments()
22. PHP 8.0 改善/変更のポイント
22
static型: 関数・クラスメソッドの戻り値に遅延静的束縛(late static binding)を
指定
<?php
class A {
public function gen1():static { return new self; }
public function gen2():static { return new static; }
}
class B extends A {}
$a = new A;
$b = new B;
var_dump($b->gen1()); // object(A)#3
var_dump($b->gen2()); // object(B)#3
RFC: https://wiki.php.net/rfc/static_return_type
TypeError: Return value of A::gen1() must
be of Type B, A returned
28. PHP 8.0 改善/変更のポイント
28
mixed型: あらゆる変数型を表す汎用の型名
array,bool,callable,int,float,null,object,resource,string
RFC: https://wiki.php.net/rfc/mixed_type_v2
<?php
class A {
public mixed $bar;
public function foo(int $value): mixed {}
}
class B extends A {
public mixed $bar;
public function foo(mixed $value): int {}
}
class A
class B
引数型:同じまたは拡大
戻り値型:同じまたは縮小
継承
リスコフ置換原理(LSP)