note 41897 added to language.oop

From: Date: Sun, 25 Apr 2004 09:47:32 +0000
Subject: note 41897 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-68763@lists.php.net to get a copy of this message
Here's how to implement the singleton programming pattern using PHP5. <?php // Singleton Pattern in PHP5 class Test { private $num; static protected $instance = null; static public function getTest() { if (Test::$instance == null) { Test::$instance = new Test(); } return Test::$instance; } protected function __construct() { $this->num = rand(0,1000); } public function getNum() { echo "NUM: " . $this->num; } } // call Singleton method instead of constructor $t1 = Test::getTest(); $t2 = Test::getTest(); // $t1 and $t2 reference the same object $t1->getNum(); $t2->getNum(); ?> ---- Manual Page -- http://www.php.net/manual/en/language.oop.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+41897 Delete -- http://master.php.net/manage/user-notes.php?action=delete+41897&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+41897&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#68763) next »