Higeath Higeath - 5 months ago 15
PHP Question

Initializing static curl in class

So I have a class for curl myCurl and I would like to use it for my 2 other classes but in those classes I want myCurl to only have one instance / be static so all objects of those other classes will use the same curl object.

class mycurl {
...
}


And the class that I want to have just one instance of MyCurl

class Company{
private static $curl=new Mycurl();
...
}


This doesn't work
syntax error, unexpected 'new' (T_NEW)

Answer

You can't initialize class instances in class body in PHP.

To make your example work, you'd have to do something like this:

class Company {
    private static $curl;

    public function __construct() {
        if (null === static::$curl) {
            static::$curl = new Mycurl();
        }
    }
}

Or, maybe a bit nicer way would be:

class Company {
    private static $curl;

    private static function curl() {
        if (null === static::$curl) {
            static::$curl = new Mycurl();
        }
        return static::$curl;
    }
}

This way, it won't be initialized until you actually need it.