note 79714 added to language.oop5.visibility

From: Date: Mon, 10 Dec 2007 07:24:10 +0000
Subject: note 79714 added to language.oop5.visibility
Groups: php.notes 
Request: Send a blank email to php-notes+get-133136@lists.php.net to get a copy of this message
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 ---- Server IP: 216.92.131.65 Probable Submitter: 218.186.14.74 (proxied: 218.212.16.27) ---- Manual Page -- http://www.php.net/manual/en/language.oop5.visibility.php Edit -- https://master.php.net/note/edit/79714 Del: integrated -- https://master.php.net/note/delete/79714/integrated Del: useless -- https://master.php.net/note/delete/79714/useless Del: bad code -- https://master.php.net/note/delete/79714/bad+code Del: spam -- https://master.php.net/note/delete/79714/spam Del: non-english -- https://master.php.net/note/delete/79714/non-english Del: in docs -- https://master.php.net/note/delete/79714/in+docs Del: other reasons-- https://master.php.net/note/delete/79714 Reject -- https://master.php.net/note/reject/79714 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#133136) next »