如何定义一个 class 只能在没有参数传递给构造函数时实例化?
How can I define a class that can only be instantiated when no parameters are passed to the constructor?
如何定义一个class只能在没有参数的情况下实例化,并且在任何参数传递给构造函数时禁止实例化?
我的目标是强制执行一组本应 "simple" 并用作模板的 classes。作为其中的一部分,我不希望在实例化期间将 任何东西 传递给构造函数。
当通过构造函数传递任何东西时,我希望事情失败(运行时错误、致命错误、静态解释器错误检查等)
class Template()
{
...
}
new Template(); // okay
new Template($anything); // must not work
如果有任何通过就抛出异常:
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();
}
如何定义一个class只能在没有参数的情况下实例化,并且在任何参数传递给构造函数时禁止实例化?
我的目标是强制执行一组本应 "simple" 并用作模板的 classes。作为其中的一部分,我不希望在实例化期间将 任何东西 传递给构造函数。
当通过构造函数传递任何东西时,我希望事情失败(运行时错误、致命错误、静态解释器错误检查等)
class Template()
{
...
}
new Template(); // okay
new Template($anything); // must not work
如果有任何通过就抛出异常:
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();
}