php构造函数

Dan*_*iel 3 php constructor

public function __construct($input = null) {
    if (empty($input)){
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

然后有一些构造函数代码......

我想要做的是如果我传递一个空变量,该类不会初始化

$ classinstance = new myClass(); 我想$ classinstance为空(或假)

我认为这是不可能的,实现类似结果的简单方法是什么?

phi*_*reo 5

您可以将普通构造函数设置为私有(因此不能在对象外部使用它,就像您创建Singleton一样)并创建工厂方法.

class MyClass {
    private function __construct($input) {
        // do normal stuff here
    }
    public static function factory($input = null) {
        if (empty($input)){
            return null;
        } else {
            return new MyClass($input);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你将实例化一个这样的类:

$myClass = MyClass::factory($theInput);
Run Code Online (Sandbox Code Playgroud)

(编辑:现在假设你只是试图支持PHP5)