Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: max(eight, five)?
(Example: nine)

The Note You're Voting On

zerocool at gameinsde dot ru
16 years ago
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(); // Object created!

$objA-> sayHello(); // Hello my name is Freddy!

$objA-> setName("Alex");

$objA-> sayHello(); // Hello my name is Alex!

$objB = MySingleton::getInstance();

$objB-> sayHello(); // Hello my name is Alex!

$objB-> setName("Bob");

$objA-> sayHello(); // Hello my name is Bob!

?>

<< Back to user notes page

To Top