note 75514 added to language.oop5.decon

From: Date: Sun, 03 Jun 2007 14:16:41 +0000
Subject: note 75514 added to language.oop5.decon
Groups: php.notes 
Request: Send a blank email to php-notes+get-127162@lists.php.net to get a copy of this message
I am not sure if the following is known or not, but here goes. I am sure most are aware of the concept of making a Class Constructor private to prevent an Object of that Class from being created as follows: <?php class A { /** * Prevent An Object From Being Constructed. */ private function __construct( ) { } } ?> In some code, if I try to do the following: <?php $Obj = new A( ); ?> PHP will fail with a fatal error. This is useful when creating Classes that are composed of only static functions or in a more advanced example, when applying the Singleton Pattern to a Class design. However what is not properly documented in this manual but is pretty simple to note, especially if you read the notes regarding the Singleton Pattern, is that you can create an Object of a Class that has a private Constructor from within the Class itself. Confused ... so am I, so allow me to provide a visual example as follows: <?php class A { /** * Prevent An Object From Being Constructed. */ private function __construct( ) { } /** * Function To Return An Instance Of This Class. */ public static function getNewInstance( ) { return new A( ); } } ?> In some code, if I try to do the following: <?php $Obj = A::getNewInstance( ); ?> PHP in this case will not fail with a fatal error and instead the variable '$Obj' becomes an Object with an instance of Class 'A'. This is a simple example and pretty advanced things can be done using this method. I am sure advanced developers are aware of this so this is just a little note going out to new PHP developers. ---- Server IP: 69.147.83.197 Probable Submitter: 217.54.224.251 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.decon.php Edit -- https://master.php.net/note/edit/75514 Del: integrated -- https://master.php.net/note/delete/75514/integrated Del: useless -- https://master.php.net/note/delete/75514/useless Del: bad code -- https://master.php.net/note/delete/75514/bad+code Del: spam -- https://master.php.net/note/delete/75514/spam Del: non-english -- https://master.php.net/note/delete/75514/non-english Del: in docs -- https://master.php.net/note/delete/75514/in+docs Del: other reasons-- https://master.php.net/note/delete/75514 Reject -- https://master.php.net/note/reject/75514 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#127162) next »