PHP Classes

File: singleton_example.php

Recommend this page to a friend!
  Classes of Simon István   cSingleton   singleton_example.php   Download  
File: singleton_example.php
Role: Example script
Content type: text/plain
Description: example
Class: cSingleton
Implements the singleton design pattern
Author: By
Last change:
Date: 15 years ago
Size: 1,905 bytes
 

Contents

Class file image Download
<?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)');

?>