微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP 8:将“资源”分配为属性、参数或返回类型

如何解决PHP 8:将“资源”分配为属性、参数或返回类型

我正在将我的项目从 PHP 7.0 更新到 PHP 8.0,但我不知道是否允许明确指定 resource 作为数据类型:

我现在知道的是:

  • resource 是构建 mixed type 的类型之一,
  • 一些内部函数,如 fopen,返回类型 resource

直到现在我读到:

我是不是在某处遗漏了什么?

感谢您抽出宝贵时间。


为了更清楚,这是我想在我的项目中使用 resource 数据类型的方式(psr-7 实现):

<?PHP

namespace MyPackages\Http\Message;

use Psr\Http\Message\StreamInterface;

/**
 * Stream.
 */
class Stream implements StreamInterface {

    /**
     * A stream,e.g. a resource of type "stream".
     *
     * @var resource
     */
    private resource $stream;

    /**
     * @param string|resource $stream A filename,or an opened resource of type "stream".
     * @param string $accessMode (optional) Access mode. 'r': Open for reading only.
     */
    public function __construct(string|resource $stream,string $accessMode = 'r') {
        $this->stream = $this->buildStream($stream,$accessMode);
    }

    /**
     * Build a stream from a filename or an opened resource of type "stream".
     *
     * Not part of psr-7.
     *
     * @param string|resource $stream Filename,or resource.
     * @param string $accessMode Access mode.
     * @return resource
     * @throws \RuntimeException If the file cannot be opened.
     * @throws \invalidargumentexception If the stream or the access mode is invalid.
     */
    private function buildStream(string|resource $stream,string $accessMode): resource {
        if (is_string($stream)) {
            //... some validations ...

            /*
             * Open the file specified by the given filename.
             * E.g. create a stream from the filename.
             * E.g. create a resource of type "stream" from the filename.
             */
            try {
                $stream = fopen($stream,$accessMode);
            } catch (\Exception $exception) {
                throw new \RuntimeException('The file "' . $stream . '" Could not be opened.');
            }
        } elseif (is_resource($stream)) {
            if ('stream' !== get_resource_type($stream)) {
                throw new \invalidargumentexception('The provided resource must be an opened resource of type "stream".');
            }
        }

        return $stream;
    }
}

解决方法

不,您不能使用 resource 输入提示。

这是 2015 年提出的 RFC,这是带有实现的 PR,这是其上的 thread of discussion

要点是 PHP 社区希望摆脱资源,因为它们代表了一种较旧的做事方式。此外,resource 过于笼统,基本上等同于 object,它没有提供太多好处(如果有的话)。

来自讨论:

这样做的原因是资源类型不合时宜 PHP 没有对象的时代,但仍然需要确定 类型的数据不透明。资源类型是一种只存在于 在内部函数之间混洗 C 指针。它没有语义 价值。因为资源现在是多余的,鉴于存在 对象,它们的时间不多了,它们将在某些时候被替换 观点。为资源添加类型声明意味着代码使用 如果我们将任何现有的资源使用替换为 对象,防止从资源迁移

安德里亚·福尔德斯

长期计划是进行类似于 GMP 的过渡 经历:它自 PHP 5.6 起使用 GMP 对象并使用资源 之前。

...

除了 Andrea 所说的(导致问题的资源类型提示应该 我们选择迁移到对象),我也认为资源类型提示 本身提供的价值相对较小。它只说你是 接受一些资源。但是,资源很多。这是一个文件吗 处理?是数据库连接吗?它是流式散列上下文吗?它 不说。

尼基塔波波夫

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。