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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)