[英]How can I define a class that can only be instantiated when no parameters are passed to the constructor?
How can I define a class that can only be instantiated without parameters, and forbids instantiation when any parameters are passed to the constructor? 如何定义一个只能在没有参数的情况下实例化的类,并在将任何参数传递给构造函数时禁止实例化?
My goal is to enforce a certain set of classes that are supposed to be "simple" and be used as a template. 我的目标是强制实施某些应该“简单”并用作模板的类。 As part of that, I don't want anything to be passed to the constructor during instantiation.
作为其一部分,我不希望在实例化过程中将任何东西传递给构造函数。
When anything is passed via constructor, I want things to fail (RunTime Error, Fatal Error, Static interpreter error check, etc) 通过构造函数传递任何内容时,我希望事情失败(运行时错误,致命错误,静态解释器错误检查等)
class Template()
{
...
}
new Template(); // okay
new Template($anything); // must not work
Just raise an exception if anything was passed: 如果任何事情通过,请提出一个例外:
class Foo {
public function __construct(...$args) {
if (count($args) > 0) {
throw new Exception('No arguments!');
}
}
}
class Test {
public function __construct() {
if (func_get_args()) {
throw new Exception('No parameters are allowed.');
}
}
}
try {
$p = new Test('test');
} catch (Exception $e) {
echo $e->getMessage();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.