沃梦达 / 编程问答 / php问题 / 正文

PHP 7 中属性的类型提示?

Type hinting for properties in PHP 7?(PHP 7 中属性的类型提示?)

本文介绍了PHP 7 中属性的类型提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

php 7 是否支持类属性的类型提示?

Does php 7 support type hinting for class properties?

我的意思是,不仅针对 setters/getters,还针对属性本身.

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 以及 docblock 结合起来.

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 中属性的类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP 7 中属性的类型提示?

基础教程推荐