Symfony 的文档暗示多重类型提示是可能的。为什么?

Symfony's documentation Implies that Multiple Type-Hinting is Possible. Why?

我原以为多重类型提示是不可能的。但是,我在 Symfony API Documentation 文档中看到了这个构造函数。

__construct(array $options = array(), AbstractProxy|NativeSessionHandler|SessionHandlerInterface|null $handler = null, MetadataBag $metaBag = null)

第二个参数,好像可以有多种类型。谁能解释一下我看到的是什么?

这是一个很好的问题,尽管答案实际上不是语言意义上的类型提示。更多文档

https://github.com/symfony/symfony/blob/7c026bb33e8ca96b285402f7fe7ae27a04a74ea9/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php#L99

是在源代码中定义的地方,没有类型提示

public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null)

https://github.com/symfony/symfony/blob/7c026bb33e8ca96b285402f7fe7ae27a04a74ea9/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php#L353

是功能存在的地方,它只是用 instanceof 检查文档中列出的所有类型提示

 if (!$saveHandler instanceof AbstractProxy &&
            !$saveHandler instanceof NativeSessionHandler &&
            !$saveHandler instanceof \SessionHandlerInterface &&
            null !== $saveHandler) {
            throw new \InvalidArgumentException('Must be instance of AbstractProxy or NativeSessionHandler; implement \SessionHandlerInterface; or be null.');
        }

这些提示被 IDE 用于一致性检查代码,正如评论中提到的 Pazi

可以在此处找到更多信息

http://www.phpdoc.org/docs/latest/guides/types.html

To be able to track which types may be used in a value you can use the pipe, or OR, (|) operator to separate each type that the associated value may be.

In the following example a method, or function, will return either a string or null as value:

/** @return string|null */ Most IDEs will recognize this format as well and offer auto-completion