Is there a simple way to make a class object global for an entire application in PHP? I need my class to only be able to be instantiated once throughout the entire application and have it working 100%.
Thanks.
EDIT
Decided the Singleton pattern is the best idea for what I need, and was requested to add a bit of code so here it is:
Using the class in my app:
function catp_check_request(){
$catp=catp::getInstance();
$dlinks=array();
$ddlinks=array();
foreach($catp->rawlinks->link as $rawlink){
$dellink="catp-del-{$rawlink->name}";
array_push($dlinks,$dellink);
}
// More stuff..
}
Declaring the class:
class catp {
private static $instance;
private $errors;
private $status_messages;
private $plugin_name;
private $plugin_shortname;
private $links;
private $linksurl;
private $rawlinks;
private function __construct(){}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new catp();
}
return self::$instance;
}
public function catp(){
$this->errors=false;
$this->plugin_name='CloakandTrack Plugin';
$this->plugin_shortname='CaTP';
$this->status_messages=array(
'updated' => 'You just updated',
'enabled' => 'You just enabled',
'disabled' => 'You just disabled',
'debug' => 'Plugin is in debug mode'
);
$this->linksurl=dirname(__FILE__).'/links.xml';
$this->rawlinks=simplexml_load_file($this->linksurl);
$this->links=$this->catp_parse_links($this->rawlinks);
}
// More functions..
}
You need singleton object.
class YourClass {
private $_instance = null;
public static function getInstance() {
if (self::$_instance == null) {
self::$_instance = new YourClass();
}
return self::$_instance;
}
}
// to get your instance use
YourClass::getInstance()->...;
Check this link for more details http://www.php.net/manual/en/language.oop5.patterns.php#language.oop5.patterns.singleton
See the singleton pattern on SO (and in which cases it is considered bad practice).
You may consider also using registry.
Note that your problem might be an architectural one and maybe there are better ways to solve the problem you face, e.g. dependency injection container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With