Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Making Class Object Global Throughout Entire Application?

Tags:

php

class

global

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

}
like image 931
Jared Avatar asked Jul 17 '11 08:07

Jared


2 Answers

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

like image 79
Eugene Manuilov Avatar answered Oct 07 '22 04:10

Eugene Manuilov


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.

like image 2
takeshin Avatar answered Oct 07 '22 02:10

takeshin