Created
November 27, 2017 12:55
-
-
Save carousel/403bb0d795e162fe58c3ee997b5f0178 to your computer and use it in GitHub Desktop.
Singleton in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Student | |
{ | |
protected static $instance; | |
public function __construct($name = null) | |
{ | |
$this->name = $name; | |
} | |
public static function instance() | |
{ | |
if (static::$instance == null) { | |
static::$instance = new static; | |
return static::$instance; | |
} else { | |
return static::$instance; | |
} | |
} | |
} | |
//helper function | |
function getStudent() | |
{ | |
return Student::instance(); | |
} | |
$studentSingleton = getStudent(); | |
$studentSingleton1 = getStudent(); | |
$student = new Student('Tamara'); | |
$student1 = new Student('Teo'); | |
$student2 = new Student('Tamara'); | |
echo 'Singletons compared by value: ' . ($studentSingleton == $studentSingleton1 ? 'true' : 'false') . "\n"; | |
echo 'Singletons compared by reference: ' . ($studentSingleton === $studentSingleton1 ? 'true' : 'false') . "\n"; | |
echo 'Objects compared by value: ' . ($student == $student1 ? 'true' : 'false') . "\n"; | |
echo 'Objects compared by reference: ' . ($student === $student1 ? 'true' : 'false') . "\n"; | |
echo 'Objects compared by value: ' . ($student == $student2 ? 'true' : 'false') . "\n"; | |
echo 'Objects compared by reference: ' . ($student === $student2 ? 'true' : 'false') . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment