How can I create a singleton in PHP?

2019-09-06 00:09发布

I'm using PDT and Aptana on Eclipse Indigo with PHP 5.3 and I want to create a singleton in a class.

By singleton, I mean I want to just have one instance of that object, and for other objects or classes to get that single instance via a function that returns that object (so this would mean I'm trying to create an object within the class that defines that object, ie: creating objA within the class objA)

I understand you can't just go a head and do this:

public $object = new Object();

with in a class definition, you have to define it in the constructor.

How can I go ahead and do this? I'm coming from Java, so it could be I'm confusing some basic stuff. Any help is greatly appreciated. Here's the code:

<?php
  class Fetcher{

    private static $fetcher = new Fetcher(); //this is where I get the unexpected "new" error

    static function getFetcherInstance(){ 
      return $this->$fetcher;
    }
  }
?>

Solved! Thanks for all the help guys!

8条回答
仙女界的扛把子
2楼-- · 2019-09-06 00:09

You might want to just read common design patterns on the php site. There are pretty good examples with good documentation:

http://www.php.net/manual/en/language.oop5.patterns.php

Else, a singleton is simply a method that returns one single instance of itself:

class MySingletonClass {

    private static $mySingleton;

    public function getInstance(){
        if(MySingletonClass::$mySingleton == NULL){
            MySingletonClass::$mySingleton = new MySingletonClass();
        }
        return MySingletonClass::$mySingleton;
    }

}
查看更多
【Aperson】
3楼-- · 2019-09-06 00:10
<?php
   class MyObject {
      private static $singleInstance;
      private function __construct() {
        if(!isset(self::$singleInstance)) {
           self::$singleInstance = new MyObject;
        }
      }
      public static function getSingleInstance() {
         return self::$singleInstance;
      }
   }
?>
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-09-06 00:13

Building on @periklis answer you might want separate singletons for different application scopes. For example, lets say you want a singleton of a database connection - fine. But what if you have TWO databases you need to connect too?

<?php
class Singleton
{
    private static $instances = array();

    public static function getInstance($name = 'default')
    {
        if ( ! isset(static::$instances[$name]))
        {
            static::$instances[$name] = new static();
        }

        return static::$instances[$name];
    }
}


Class DB extends Singleton {}


$db_one = DB::getInstance('mysql');
$db_two = DB::getInstance('pgsql');
查看更多
\"骚年 ilove
5楼-- · 2019-09-06 00:16

Alse define __clone method

class Fetcher {

    protected static $instance;

    private function __construct() {
        /* something */
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Fetcher();
        }
        return self::$instance;
    }

    private function __clone() {
        /* if we want real singleton :) */
        trigger_error('Cannot clone', E_USER_ERROR);
    }
}
查看更多
Animai°情兽
6楼-- · 2019-09-06 00:24

try this:

<?php
class myclass{
    private static $_instance = null;

    public static function getInstance() {
        if (self::$_instance === null) {
            self::$_instance = new myclass();
        }

        return self::$_instance;
    }
}
?>

and call it with:

<?php
$obj = myclass::getInstace();
?>
查看更多
成全新的幸福
7楼-- · 2019-09-06 00:27

You cannot assign a class property in PHP like that. It must be a scalar, or array value, or the property must be set in a method call.

protected static $fetcher;

static function getFetcherInstance(){ 
    if (!self::$fetcher) {
        self::$fetcher = new Fetcher();
    }
    return self::$fetcher;
}

Also, notice that I did not use $this->, as that only works for object instances. To work with static values you need to use self:: when working within the class scope.

查看更多
登录 后发表回答