Reputation: 2121
I created a singleton class in PHP:
<?php
class DataManager
{
private static $dm;
// The singleton method
public static function singleton()
{
if (!isset(self::$dm)) {
$c = __CLASS__;
self::$dm = new $c;
}
return self::$dm;
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function test(){
print('testsingle');
echo 'testsingle2';
}
function __get($prop) {
return $this->$prop;
}
function __set($prop, $val) {
$this->$prop = $val;
}
}
?>
Now when I try to use this class in my index.php:
<?php
include('Account/DataManager.php');
echo 'test';
$dm = DataManager::singleton();
$dm->test();
echo 'testend';
?>
the only echo I get, is 'test', the function test() in the singleton class, is never called so it seems. Also the 'testend' at the end of the index.php is never been called.
Is there an error in my singleton class?
Upvotes: 0
Views: 120
Reputation: 9874
The code looks fine to me, although I haven't tested it. I would however advise you to create a private or protected (but not public) constructor, since you only want to be able to create an instance from inside your class (in DataManager::singleton()
)
Upvotes: 1