Hi, here's my simple Singleton example, i think it can be useful for someone. You can use this pattern to connect to the database for example.
<?php
class MySingleton
{
private static $instance = null;
private function __construct()
{
$this-> name = 'Freddy';
}
public static function getInstance()
{
if(self::$instance == null)
{
print "Object created!<br>";
self::$instance = new self;
}
return self::$instance;
}
public function sayHello()
{
print "Hello my name is {$this-> name}!<br>";
}
public function setName($name)
{
$this-> name = $name;
}
}
$objA = MySingleton::getInstance(); $objA-> sayHello(); $objA-> setName("Alex");
$objA-> sayHello(); $objB = MySingleton::getInstance();
$objB-> sayHello(); $objB-> setName("Bob");
$objA-> sayHello(); ?>