Global PHP class in functions?

孤街浪徒 提交于 2020-01-23 08:37:07

问题


Is there a way to access one instance of a class inside functions in PHP? Like this:

include("class.php");
$bla=new Classname();

function aaa(){
    $bla->DoSomething();  //Doesn't work.
}

$bla->DoSomething();  //Works.

回答1:


If I interpret your question correctly, then the proper way to do this is create a singleton class.

class Singleton {
    private static $instance;

    private function __construct() {}
    private function __clone() {}

    public static function getInstance() {
        if (!Singleton::$instance instanceof self) {
             Singleton::$instance = new self();
        }
        return Singleton::$instance;
    }

    public function DoSomething() {
        ...
    }
}

You would call this in your function as follows :

function xxx() {
    Singleton::getInstance()->DoSomething();
}



回答2:


Use global:

function aaa() {
    global $bla;
    $bla->DoSomething();
}

Works on all variables, not just classes.




回答3:


The cleaner way would be to pass the instance by reference to the given class and then access it.

Another way would be to use a singleton pattern, though many argue that it's not really better than a global.




回答4:


As already answered, you could use a global variable to store the class instance, but it sounds to me like you should consider using something like the Singleton pattern instead for a cleaner implementation.

You can find a simple example of a singleton class here.




回答5:


If you want to enforce using only a single instance of a class throughout your application, you should use a singleton, not a global. You could do something like this:

class Classname {
    private static $instance;

    private function __construct()  {...}

    public function doSomething() {...}

    // The singleton method
    public static function singleton()  {
        if ( !isset(self::$instance) ) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    private function __clone() { /* do nothing here*/ }
}


function aaa() {
    Classname::getInstance()->doSomething();
}


来源:https://stackoverflow.com/questions/2247354/global-php-class-in-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!