Location: PHPKode > scripts > cSingleton > csingleton/singleton_example.php
<?php

include 'cSingleton.php';

/**
 * Example
 */
// Simple class
class A extends aSingleton
{
	protected $prefix = 'A_';

	function __construct__()
	{
		echo "Create a new 'A' instance.</br>";
	}

	function write($text)
	{
		echo $this->prefix.$text.'</br>';
	}

	function setPrefix($prefix)
	{
		$this->prefix = $prefix;
	}
}

// Extended singleton class
class B extends A
{
	protected $prefix = 'B_';

	function __construct__()
	{
		echo "Create a new 'B' instance.</br>";
	}

	function plusz($a, $b)
	{
		echo $this->prefix.($a + $b).'</br>';
	}
}

// Singleton class with construct parameter.
class C extends aSingleton
{
	protected $prefix;

	function __construct__()
	{
		$l_Arguments = func_get_args();

		$this->setPrefix($l_Arguments[0]);

		echo "Create a new 'C' instance.</br>";
	}

	function write($text)
	{
		echo $this->prefix.$text.'</br>';
	}

	function setPrefix($prefix)
	{
		$this->prefix = $prefix;
	}
}

echo 'cSingleton v0.1 & aSingleton v0.1</br>';
echo '------------------------------------------------------</br>';

// Create a new 'A' class.
$a = new A();
$a->write('HIHI(a)');
// This drop a E_USER_ERROR
// $aa = new A();
// $aa->write('HIHI(a)');

// Create a new 'B' class with cSingleton.
$b = cSingleton::getInstance('B');
$b->plusz(1,6);
$b->write('HIHI(b)');

// Create a new 'C' class.
// Created with one parameter.
$c = cSingleton::getInstance('C', ':)_');
$c->write('HEHE(c)');

// The 'vmi_' isn't saved becouse only once use the constructor.
$d = cSingleton::getInstance('C', 'vmi_');
// Get the 'C' class instance.
$e = cSingleton::getInstance('C');
// Later PHP 5.3
// $f = C::getInstance();

$d->write('HEHE(d)');
$e->write('HEHE(e)');
// $f->write('HEHE(f)');

// Set a new prefix
echo 'd-nél prefix váltás :D -re</br>';
$d->setPrefix(':D_');

// One instance. :)
$c->write('LOL(c)');
$d->write('LOL(d)');
$e->write('LOL(e)');
// $f->write('HEHE(f)');

?>
Return current item: cSingleton