I have an object of some class that obeys the singleton pattern. I need to initialize it in one file and then use it in others. I don’t know how to do this, here is what I tried :
//myClass.php
class myClass
{
private static $instance = null;
private function __construct($args)
{
//stuff
}
public function Create($args)
{
self::$instance = new myClass($args);
return self::$instance;
}
public function Get()
{
return self::$instance;
}
}
//index.php
<?php
require_once('myClass.php');
$instance = myClass::Create($args);
?>
<a href="test.php">Test Me!</a>
//test.php
echo(is_null(myClass::Get())); //displays 1
So the problem is that from test.php, myClass::get() always returns null!
I have also tried to store the instance in the $_SESSION, which gives me the same result. Can you please point me in the right direction?
You should include file with the class difinition in each file where it used (and it should be included before it will in use).
BTW
You don’t need to define those two methods
CreateandGet. You can create only one method calledgetInstance:And then you can use it like:
UPD
If you have to put some arguments into constructor just use predefined arguments:
ANSWER
Sorry that you have to scroll a few screens to find this =)))
The reason why you can’t use
myClass::Get()in you context is that you have 2 scripts that means – two different programs.Singleton should be used within a single application (one script).
So in your case, correct usage will be module system:
– index.php
– main.php
– test.php
And your links will be: