Re: private/public __construct in PHP / Singleton pattern

From: Date: Sun, 05 Jun 2005 22:19:27 +0000
Subject: Re: private/public __construct in PHP / Singleton pattern
References: 1  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-37989@lists.php.net to get a copy of this message
Joe Stump wrote:
I've ran across what I feel is a bug in PHP5's OOP. I'm trying to create a singleton pattern, but PHP5 doesn't allow you to do this with base classes with public __construct() it appears. For instance: <?php abstract class A {
    public function __construct()
    {
        echo __CLASS__;
    }
} class B extends A {
    private static $instance;
    private function __construct()
    {
        parent::__construct();
    }
    public static function singleton()
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }
} $b = B::singleton(); ?> Results in the following error: <br /> <b>Fatal error</b>: Access level to B::__construct() must be public (as in class A) in <b>/usr/local/httpd/htdocs/framework/foo.php</b> on line <b>29</b><br /> Am the the only one that finds this retarded? --Joe
Per the documentation, you can only open-up the declaration (say, from private to protected to public) but not the other way around. I think you could resolve that by using "protected" on the A::__construct() and "final protected" on B::__construct() That will prevent people from directly creating instances, if I get what you're trying to do. -Philippe

« previous php.pear.dev (#37989) next »