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.
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();
}
Use global:
function aaa() {
global $bla;
$bla->DoSomething();
}
Works on all variables, not just classes.
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