0

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?

Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
Oritm
  • 2,113
  • 2
  • 25
  • 40

1 Answers1

1

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())

Arjan
  • 9,784
  • 1
  • 31
  • 41
  • Weird, i used MAMP for macosx. Apparently MAMP does not work the way i want. I now tested it on a Windows machine, Xampp installed and it indeed works fine. I'm considering in not using singleton.. thanks arjan, thank netcoder and gordon! – Oritm Apr 28 '11 at 22:33