如何在PHP中创建单例? [英] How can I create a singleton in PHP?

查看:169
本文介绍了如何在PHP中创建单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



我明白你不能只需要去做一下这个:

  public $ object = new Object(); 

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



我该怎么办呢?我来自Java,所以可能会混淆一些基本的东西。任何帮助是极大的赞赏。以下是代码:

 <?php 
class Fetcher {

private static $ fetcher = new Fetcher(); //这是我得到意想不到的新错误

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

已解决!感谢所有帮助的人!

解决方案

尝试这个:

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


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!

解决方案

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

这篇关于如何在PHP中创建单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆