Plz tell me where i'm doing wrong...
I've 3 classes. These are like this..
- Singleton class where i'm following singleton design pattern
- Class ram
- Class sam
In 'ram' class i'm setting data for singleton class object.
Now, in 'sam' class.. i'm trying to access singleton class object inside show_data() function of sam class.
When, i'm using..
Print_r($this) : showing empty object
but, when i'm using following code..
$singleton_obj = Singleton::getInstance();
print_r($singleton_obj); : Showing content of singleton object
My question is, why in-case of Print_r($this) it's showing empty object. Is there any way, i can get content of singleton class object by using Print_r($this).
MY class file is 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();
?>