如何在 PHP 中创建单例?

发布于 2024-12-27 02:02:09 字数 618 浏览 4 评论 0原文

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

通过单例,我的意思是我只想拥有该对象的一个​​实例,而其他对象或类则通过返回该对象的函数来获取该单个实例(因此这意味着我正在尝试在类中创建一个对象定义该对象,即:在类 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;
    }
  }
?>

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

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

画中仙 2025-01-03 02:02:09

试试这个:

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

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();
?>
羁〃客ぐ 2025-01-03 02:02:09

还定义 __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);
    }
}

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);
    }
}
淡淡離愁欲言轉身 2025-01-03 02:02:09

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

protected static $fetcher;

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

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

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.

情泪▽动烟 2025-01-03 02:02:09

您可能只想阅读 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;
    }

}

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

}
独闯女儿国 2025-01-03 02:02:09

基于 @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');

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');
机场等船 2025-01-03 02:02:09

基本上实现单例模式意味着编写一个带有私有构造函数和静态方法来构建自身的类。另请检查 PHP 网站: http://www.php.net/manual /en/language.oop5.phphttps://www.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

Basically implementing a singleton pattern means writing a class with a private constructor and a static method to build itself. Also check PHP site for it: http://www.php.net/manual/en/language.oop5.php and https://www.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
執念 2025-01-03 02:02:09
<?php
   class MyObject {
      private static $singleInstance;
      private function __construct() {
        if(!isset(self::$singleInstance)) {
           self::$singleInstance = new MyObject;
        }
      }
      public static function getSingleInstance() {
         return self::$singleInstance;
      }
   }
?>
<?php
   class MyObject {
      private static $singleInstance;
      private function __construct() {
        if(!isset(self::$singleInstance)) {
           self::$singleInstance = new MyObject;
        }
      }
      public static function getSingleInstance() {
         return self::$singleInstance;
      }
   }
?>
倥絔 2025-01-03 02:02:09
class MyClass {

    private static $instance;

    public static function getInstance() {
        if( !isset( self::$instance ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

}

然后使用调用获取实例
MyClass::getInstance();

class MyClass {

    private static $instance;

    public static function getInstance() {
        if( !isset( self::$instance ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

}

Then call get instance using
MyClass::getInstance();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文