PHP Creating a class object globally throughout the application?

Is there an easy way to make a class object global for an entire PHP application? I need my class so that it can be created only once throughout the application and it will work 100%.

Thanks.

EDIT

The solved Singleton template is the best idea for what I need, and I was asked to add some code, here it is:

Using a class in my application:

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.. } 

Class declaration:

 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.. } 
+4
source share
3 answers

You need a single 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 out this link for more information http://www.php.net/manual/en/language.oop5.patterns.php#language.oop5.patterns.singleton

+6
source

See singleton pattern on SO (and when is this considered bad practice).

You can also use registry .

Please note that your problem may be architectural, and there may be more effective ways to solve the problem you are facing, for example. container for injection.

+2
source

You can use the __autoload function to dynamically enable this class.

http://www.electrictoolbox.com/php-autoload/

0
source

All Articles