【发布时间】:2019-12-02 01:36:03
【问题描述】:
在 PHP 中使用类常量,是否可以强制参数必须是常量之一(如 Enum)?
Class Server {
const SMALL = "s";
const MEDIUM = "m";
const LARGE = "l";
private $size;
public function __construct($size) {
$this->size = $size
}
}
$small = new Server(Server::SMALL); // valid
$foobar = new Server("foobar"); // also valid. This should fail instead
new Server("foobar") 的情况应该会失败,但是因为构造函数没有验证 $size 这有效。为简洁起见,我只列出了三个常量大小,但假设有 N 个大小,所以不想做大量的 if 检查。
【问题讨论】:
-
您可以强制参数为 int。这个
__construct(int $size)这种方式直接传递字符串会失败。你得到一个类型错误:Uncaught TypeError: Argument 1 passed to Server::__construct() must be of the type int, string given, -
PHP and Enumerations 的可能副本,PHP 也有可能适合您的 splenum。