Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global PHP class in functions?

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.
like image 981
MilMike Avatar asked Nov 30 '22 11:11

MilMike


2 Answers

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();
}
like image 139
wimvds Avatar answered Dec 04 '22 11:12

wimvds


Use global:

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

Works on all variables, not just classes.

like image 28
Tatu Ulmanen Avatar answered Dec 04 '22 11:12

Tatu Ulmanen