我正在将我的项目从 PHP 7.0 更新到 PHP 8.0,但我无法确定是否允许将其明确指定为resource
数据类型:
- 一个类属性,
- 方法/函数参数的,
- 由方法/函数返回,
我现在所知道的是:
直到现在我读到:
- 有关迁移到 PHP 8 的所有官方手册:PHP:从 PHP 5.5.x 迁移到 PHP 5.6.x,...,PHP:从 PHP 7.4.x 迁移到 PHP 8.0.x;
- PHP.Watch上的全部内容:PHP 版本;
- Lindevs上的全部内容: PHP 。
我在某个地方错过了什么吗?
感谢您的时间。
为了更清楚起见,这就是我想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;
}
}