How to make an object globally accessible
Hi, I have a small collection of classes, some of which should be available globally.
I found something similar in Zend_Registry, but reading its code, I cannot figure out how a call to a static function can return an initialized instance of a class ...
I need to do something like:
<?php
//index.php
$obj = new myUsefulObject();
$obj->loadCfg("myFile.xml");
$req = new HTTPRequest();
$req->filter("blablabla");
myappp::registerClass("object",$obj);
myappp::registerClass("request",$req);
$c = new Controller();
$c->execute();
?>
Here I have filtered the Request object and I want the controller to be able to receive this already filtered request.
<?php
class Controller
{
function __construct()
{
$this->request = Application::getResource("request");//This must be the filtered var =(
}
}
?>
I don't know how to implement this Application :: getResource (), the only thing I know is that it must be a static method because it cannot be associated with a specific instance.
source to share
Besides static methods, PHP also has static properties: properties that are local to the class. This can be used to implement singletons, or indeed a registry:
class Registry {
private static $_registry;
public static function registerResource($key, $object)
{
self::$_registry[$key] = $object;
}
public static function getResource($key) {
if(!isset(self::$_registry[$key]))
throw InvalidArgumentException("Key $key is not available in the registry");
return self::$_registry[$key];
}
}
source to share
1: you can use global variables with the keyword global
:
$myVar = new SomethingProvider();
class MyClass {
public function __construct() {
global $myVar;
$myVar->doSomething();
}
}
2: You can do the same using $GLOBALS
super-global:
$myVar = new SomethingProvider();
class MyClass {
public function __construct() {
$GLOBALS['myVar']->doSomething();
}
}
3: You can define a singleton class (wikipedia has a good example ).
4: You can add global variables as public static members (or private static members with public getters / setters) to the class:
class Constants {
const NUM_RETIES = 3;
}
if ($tries > Constants::NUM_RETRIES) {
# User failed password check too often.
}
class Globals {
public static $currentUser;
}
Globals::$currentUser = new User($userId);
I would not recommend the first two methods, overwriting the values ββof these globals too unintentionally.
source to share