【问题标题】:How can I create a singleton in PHP?如何在 PHP 中创建单例?
【发布时间】:2012-01-13 20:23:29
【问题描述】:

我在带有 PHP 5.3 的 Eclipse Indigo 上使用 PDT 和 Aptana,我想在一个类中创建一个单例。

通过单例,我的意思是我只想拥有该对象的一个​​实例,而其他对象或类通过返回该对象的函数获取该单个实例(所以这意味着我正在尝试创建一个对象在定义该对象的类中,即:在类 objA 中创建 objA)

我知道你不能只管这样做:

public $object = new Object();

在类定义中,你必须在构造函数中定义它。

我怎样才能继续这样做?我来自Java,所以我可能混淆了一些基本的东西。任何帮助是极大的赞赏。代码如下:

<?php
  class Fetcher{

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

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

已解决!感谢大家的帮助!

【问题讨论】:

    标签: php eclipse singleton aptana eclipse-pdt


    【解决方案1】:

    试试这个:

    <?php
    class myclass{
        private static $_instance = null;
    
        public static function getInstance() {
            if (self::$_instance === null) {
                self::$_instance = new myclass();
            }
    
            return self::$_instance;
        }
    }
    ?>
    

    并调用它:

    <?php
    $obj = myclass::getInstace();
    ?>
    

    【讨论】:

    • 如果你想全局单例更改为self::$_instance = new static();
    【解决方案2】:

    你不能像这样在 PHP 中分配一个类属性。它必须是标量或数组值,或者必须在方法调用中设置属性。

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

    另外,请注意我没有使用$this-&gt;,因为它只适用于对象实例。要使用静态值,您需要在类范围内使用 self::

    【讨论】:

      【解决方案3】:

      您可能只想阅读 php 网站上的常见设计模式。有很好的例子和很好的文档:

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

      否则,单例只是一种返回自身单个实例的方法:

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

      【讨论】:

        【解决方案4】:

        在@periklis 答案的基础上,您可能需要针对不同的应用程序范围使用单独的单例。例如,假设您想要一个单一的数据库连接 - 很好。但是,如果您还需要连接两个数据库怎么办?

        <?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');
        

        【讨论】:

          【解决方案5】:

          另外定义__clone方法

          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);
              }
          }
          

          【讨论】:

            【解决方案6】:

            基本上实现单例模式意味着编写一个带有私有构造函数和静态方法的类来构建自身。另请检查 PHP 站点:http://www.php.net/manual/en/language.oop5.phphttp://it2.php.net/manual/en/book.spl.php

            class A {
            protected $check;
            private function __construct($args) {
            }
            static public function getSingleton($args) {
                static $instance=null;
                if (is_null($instance)) {
                    $instance=new A();
                }
                return $instance;
            }
            public function whoami() {
                printf("%s\n",spl_object_hash($this));
            }
            }
            $c=A::getSingleton("testarg");
            $d=A::getSingleton("testarg");
            $c->whoami(); // same object hash
            $d->whoami(); // same object hash
            $b= new A("otherargs"); // run time error
            

            【讨论】:

              【解决方案7】:
              <?php
                 class MyObject {
                    private static $singleInstance;
                    private function __construct() {
                      if(!isset(self::$singleInstance)) {
                         self::$singleInstance = new MyObject;
                      }
                    }
                    public static function getSingleInstance() {
                       return self::$singleInstance;
                    }
                 }
              ?>
              

              【讨论】:

                【解决方案8】:
                class MyClass {
                
                    private static $instance;
                
                    public static function getInstance() {
                        if( !isset( self::$instance ) ) {
                            self::$instance = new self();
                        }
                
                        return self::$instance;
                    }
                
                }
                

                然后调用 get instance using MyClass::getInstance();

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2020-04-24
                  • 2012-05-28
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多