note 79714 deleted from language.oop5.visibility by felipe

From: Date: Sat, 15 Dec 2007 15:46:05 +0000
Subject: note 79714 deleted from language.oop5.visibility by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-133582@lists.php.net to get a copy of this message
Note Submitter: boltclock aInACircle NOVALISTIC dot com ---- According to Example #2, all constructors must be public. However, PHP does not seem to mind even if you declare a constructor as protected or private. Here's an example of a simple singleton class with a private constructor: <?php class Singleton { private $foo = ''; private function __construct($foo) { echo "Constructed (should happen only once): \$foo is $foo\n"; $this->foo = $foo; } public static function get_instance($foo) { echo "About to call constructor: \$foo is $foo - not assigned yet\n"; static $instance; if (!$instance instanceof Singleton) { $instance = new Singleton($foo); } return $instance; } public function get_foo() { return "The singleton's \$foo is {$this->foo}"; } } // These work $foo = Singleton::get_instance('foo'); echo $foo->get_foo() . "\n"; $bar = Singleton::get_instance('bar'); echo $bar->get_foo() . "\n"; // Constructor was declared private, this shouldn't work new Singleton('baz'); ?> You get this output: About to call constructor: $foo is foo - not assigned yet Constructed (should happen only once): $foo is foo The singleton's $foo is foo About to call constructor: $foo is bar - not assigned yet The singleton's $foo is foo PHP Fatal error: Call to private Singleton::__construct() from invalid context in D:\singleton.php on line 39

« previous php.notes (#133582) next »