问题描述
php 7是否支持类属性的类型提示?
Does php 7 support type hinting for class properties?
我的意思是,不仅是针对设置者/获取者" ,而且还针对财产本身.
I mean, not just for setters/getters but for the property itself.
类似的东西:
class Foo {
/**
*
* @var Bar
*/
public $bar : Bar;
}
$fooInstance = new Foo();
$fooInstance->bar = new NotBar(); //Error
推荐答案
PHP 7.4 将支持类型化属性像这样:
PHP 7.4 will support typed properties like so:
class Person
{
public string $name;
public DateTimeImmutable $dateOfBirth;
}
PHP 7.3和更早版本不支持此功能,但是有一些替代方法.
PHP 7.3 and earlier do not support this, but there are some alternatives.
您可以创建一个私有属性,该私有属性只能通过具有类型声明的getter和setter进行访问:
You can make a private property which is accessible only through getters and setters which have type declarations:
class Person
{
private $name;
public function getName(): string {
return $this->name;
}
public function setName(string $newName) {
$this->name = $newName;
}
}
您还可以设置公共属性,并使用docblock向阅读代码和使用IDE的人员提供类型信息,但这不提供运行时类型检查:
You can also make a public property and use a docblock to provide type information to people reading the code and using an IDE, but this provides no runtime type-checking:
class Person
{
/**
* @var string
*/
public $name;
}
实际上,您可以将getter和setter以及一个文档块结合在一起.
And indeed, you can combine getters and setters and a docblock.
如果您更喜欢冒险,可以使用 __get
,__set
,__isset
和__unset
魔术方法,然后自己检查类型.不过,我不确定是否会推荐.
If you're more adventurous, you could make a fake property with the __get
, __set
, __isset
and __unset
magic methods, and check the types yourself. I'm not sure if I'd recommend it, though.
这篇关于为PHP 7中的属性键入提示吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!