Php constructors

public function __construct($input = null) {
    if (empty($input)){
        return false;
    }

and then some constructor code ...

what I would like to do is not initialize the class if I pass an empty variable

$ classinstance = new myClass (); I want $ classinstance to be empty (or false)

I think this is impossible, like this. What is an easy way to achieve a similar result?

+3
source share
3 answers

You can make a regular constructor private (therefore, it cannot be used from outside the object, as if you were doing a Singleton ) and create a Factory Method .

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);
        }
    }
}

Then you must create an instance of the class as follows:

$myClass = MyClass::factory($theInput);

(EDIT: it is now assumed that you are only trying to support PHP5)

+5

factory :

private function __construct($input = null) {
}

public static function create($input = null) {
    if (empty($input)) {
        return false;
    }
    return new MyObject($input);
}    
+1

, . print_r , .

You can make it throw an exception, but it is unlikely to be the style you want.

+1 to factory already published methods. These factory methods may also be:

public static function newCreate( $a ) { return ( !$a ) ? false : new foo( $a ); }

I like factory methods :-)

0
source

Source: https://habr.com/ru/post/1721449/


All Articles