Here is my situation:
On my home page I initialize my singleton this way:
mypage.com/index.php
<?php
include ('includes/userfactory.php');
session_start();
$userFactory = UserFactory::instance();
//make random number 10 to 100
$userFactory->MakeRandomNumber();
$userFactory->Print();
?>
<!DOCTYPE html>
<html>
<head>
My Page
</head>
<body>
<li class="nav-item"><a href="newlink">go to new link</a></li>
</body>
</html>
And when I click an href link to navigate to another page, on that page I try to call the singleton instance I previously created and then check my random number to see if it is the same as before.
mypage.com/newlink/index.php
<?php
include ('../includes/userfactory.php');
session_start();
$userFactory = UserFactory::instance();
$userFactory->Print();
?>
The thing is that on the second page the random number is not even generated yet, so it creates another instance of the supposed singleton.
This is my userfactory which extends Singleton class.
userfactory.php
<?php
include ('singleton.php');
class UserFactory extends Singleton
{
private $randomNumber = 0;
private $isLive = false;
public function Print()
{
echo "My random number is: ".$this->$randomNumber;
}
public function MakeRandomNumber()
{
if($this->$randomNumber == 0)
{
$this->$randomNumber = rand(10,100);
}
}
}
?>
And here is my Singleton pattern I copied from this thread
singleton.php
<?php
/**
* Singleton Pattern.
*
* Modern implementation.
*/
class Singleton
{
/**
* Call this method to get singleton
*/
public static function instance()
{
static $instance = false;
if( $instance === false )
{
// Late static binding (PHP 5.3+)
$instance = new static();
}
return $instance;
}
/**
* Make constructor private, so nobody can call "new Class".
*/
private function __construct() {}
/**
* Make clone magic method private, so nobody can clone instance.
*/
private function __clone() {}
/**
* Make sleep magic method private, so nobody can serialize instance.
*/
private function __sleep() {}
/**
* Make wakeup magic method private, so nobody can unserialize instance.
*/
private function __wakeup() {}
}
?>