【发布时间】:2012-07-08 09:57:48
【问题描述】:
请告诉我哪里做错了...
我有 3 节课。这些是这样的..
- 我遵循单例设计模式的单例类
- 类内存
- 类山姆
在“ram”类中,我正在为单例类对象设置数据。
现在,在“sam”类中。我正在尝试访问 sam 类的 show_data() 函数中的单例类对象。
什么时候,我正在使用..
Print_r($this) : showing empty object
但是,当我使用以下代码时..
$singleton_obj = Singleton::getInstance();
print_r($singleton_obj); : Showing content of singleton object
我的问题是, 为什么在 Print_r($this) 的情况下它显示的是空对象。有什么办法,我可以使用 Print_r($this) 获取单例类对象的内容。
我的类文件是这个..
<?php
class Singleton
{
// A static property to hold the single instance of the class
private static $instance;
// The constructor is private so that outside code cannot instantiate
public function __construct() { }
// All code that needs to get and instance of the class should call
// this function like so: $db = Database::getInstance();
public function getInstance()
{
// If there is no instance, create one
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Block the clone method
private function __clone() {}
// Function for inserting data to object
public function insertData($param, $element)
{
$this->{$param} = $element;
}
}
//---CLASS ram---
class ram
{
function __construct()
{
$db = Singleton::getInstance();
$db->insertData('name', 'Suresh');
}
}
$obj_ram = new ram;
//---CLASS sam---
class sam extends Singleton
{
function __construct()
{
parent::__construct();
}
public function show_data()
{
echo "<br>Data in current object<br>";
print_r($this);
echo "<br><br>Data in singleton object<br>";
$singleton_obj = Singleton::getInstance();
print_r($singleton_obj);
}
}
$obj_sam = new sam;
echo $obj_sam->show_data();
?>
【问题讨论】:
-
如果您的 insertData 函数有一个额外的 },至少在此处的代码中不确定这只是一个错字还是您的代码中是否存在。
-
为什么 getInstance 不是静态方法?
-
您的评论说 __construct() 是
private但您的代码声明它是公开的? -
@Laxus 它需要是静态的吗?我对 PHP 的 OOP 知识并不深入。顺便说一句,即使我将其更改为静态,它也不会产生任何效果。
-
您的代码按预期运行。你不应该尝试扩展单例。这不是使用模式的方式。您只需要一个 Singleton 实例 - 没有克隆或子项。