note 113689 added to language.oop5.static
| From: | desmatic | Date: | Sat, 16 Nov 2013 09:40:05 +0000 |
| Subject: | note 113689 added to language.oop5.static | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-197539@lists.php.net to get a copy of this message | ||
Don't use GLOBALS in classes (or anywhere really), use static variables instead. They're
better. They can do everything a GLOBAL can and they can be protected by accessor functions so
they'll never get clobbered.
class foo {
private static $_private = null;
public function get() {
if (self::$_private === null) {
self::$_private = new stdClass();
}
return self::$_private;
}
}
class bar extends foo {
}
function scope_foo() {
$f = new foo();
$f->get()->name = "superdude";
}
function scope_bar() {
$b = new bar();
$b->get()->description = "an object reference test";
}
scope_foo();
scope_bar();
$my = new bar();
foreach ($my->get() as $key => $value) {
echo "{$key} => {$value}\n";
}
outputs:
name => superdude
description => an object reference test
----
Server IP: 72.52.91.14
Probable Submitter: 72.52.91.14
----
Manual Page -- http://php.net/manual/en/language.oop5.static.php
Edit -- https://master.php.net/note/edit/113689
Del: integrated -- https://master.php.net/note/delete/113689/integrated
Del: useless -- https://master.php.net/note/delete/113689/useless
Del: bad code -- https://master.php.net/note/delete/113689/bad+code
Del: spam -- https://master.php.net/note/delete/113689/spam
Del: non-english -- https://master.php.net/note/delete/113689/non-english
Del: in docs -- https://master.php.net/note/delete/113689/in+docs
Del: other reasons-- https://master.php.net/note/delete/113689
Reject -- https://master.php.net/note/reject/113689
Search -- https://master.php.net/manage/user-notes.php