note 27512 added to language.oop

From: Date: Mon, 09 Dec 2002 13:55:01 +0000
Subject: note 27512 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-40570@lists.php.net to get a copy of this message
If you want to use class variables you should use a static method, not a global as suggested above. class Counter { function Counter($name) { $this->name = $name; $this->id = Counter::id(); } function &_classObj() { static $classObj; if(!is_object($classObj)) { $classObj = new stdClass(); $classObj->id=0; } return $classObj; } function id() { $co =& Counter::_classObj(); $co->id++; return $co->id; } function sayHello() { echo "Hello, I am $this->name and my ID is $this->id\n"; } } $a = new Counter("Bill"); $b = new Counter("Ben"); $a->sayHello(); $b->sayHello(); **** Prints **** Hello, I am Bill and my ID is 1 Hello, I am Ben and my ID is 2 -- http://www.php.net/manual/en/language.oop.php http://master.php.net/manage/user-notes.php?action=edit+27512 http://master.php.net/manage/user-notes.php?action=delete+27512 http://master.php.net/manage/user-notes.php?action=reject+27512

« previous php.notes (#40570) next »