如何在 PHP 中创建单例? [英] How can I create a singleton in PHP?
问题描述
我在带有 PHP 5.3 的 Eclipse Indigo 上使用 PDT 和 Aptana,我想在类中创建一个单例.
I'm using PDT and Aptana on Eclipse Indigo with PHP 5.3 and I want to create a singleton in a class.
通过单例,我的意思是我只想拥有该对象的一个实例,并且其他对象或类通过返回该对象的函数获取该单个实例(因此这意味着我正在尝试创建一个对象在定义该对象的类中,即:在类 objA 中创建 objA)
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.
我该如何继续执行此操作?我来自 Java,所以可能是我混淆了一些基本的东西.任何帮助是极大的赞赏.代码如下:
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;
}
}
?>
已解决!感谢大家的帮助!
推荐答案
试试这个:
<?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();
?>
这篇关于如何在 PHP 中创建单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!