简体   繁体   English

如何定义一个仅在没有参数传递给构造函数时才能实例化的类?

[英]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.

相关问题 我可以在Class构造函数中定义一个对象吗? - Can i define an object inside a Class constructor? 仅当类在php中实例化时,我才能要求类函数吗? - Can I require class-functions only if the class is instantiated in php? 检查类是否可以在没有参数的情况下实例化 - Check if class can be instantiated without parameters 我们只能在类的构造函数中定义匿名函数吗? - Can we only define anonymous function inside constructor of class? PHP - 只能由另一个类实例化的类 - PHP - Class that can be instantiated only by another class 类实例化到对象后,如何传递__construct参数? - can I pass __construct parameters after a class has been instantiated into an object? 对于PHP REST API,如何在类定义之外定义/设置数据库连接参数? - For PHP REST API, how can I define/set the database connection parameters outside the class definition? 更改类中的构造函数参数后,如何标记任何需要更新的子类? - After changing constructor parameters in a class, how can I mark any of child classes that need to be updated too? 抽象类不能被实例化如何执行 - How can an abstract class be executed if it cannot be instantiated 如何在Laravel 5中定义默认路由参数 - How can I define default route parameters in Laravel 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM