
76
|
第
3
章
型标注将同时作用于属性及对应参数。你还可以对升级版的参数设置默认值:
class User
{
public function
__construct(
private
int $id,
private
string $name = '') {
}
}
3.6
属性
属性(
attribute
)是个语法扩展,这项扩展可以使你对函数、方法、类、接口还有
trait
添加元数据。然后添加一般的
PHP
的反射
API
,就可以访问这些元数据了。
属性是结构化的信息替代,通常用于文档注释的编码。它通过反射的编程方式变得可用,
从而替代了要求一个独立的程序去解析这个信息。这里有一个例子,用于解释在文档注
释中使用它:
/**
*
MyFeatureTestCase
*
* @
owner oyamauchi
* @
deprecated
*/
class MyFeatureTestCase extends
TestCase {
// ...
}
/**
*
MyFeatureTestCase with attributes
*/
<<Owner('oyamauchi'), Deprecated>>
class MyFeatureTestCaseWithAttributes extends
TestCase {
// ...
}
3.6.1
属性语法
每个属性都是
key
到数组中
value
的映射。
key
都是字符串,而
value
是标量(
null
、布
尔型字面量、数字型字面量、字符串字面量,或者它们的数组)。
语法非常简单,在一个函数、方法、类、接口或者 ...