Skip to content

Instantly share code, notes, and snippets.

@carousel
Created November 27, 2017 12:55
Show Gist options
  • Save carousel/403bb0d795e162fe58c3ee997b5f0178 to your computer and use it in GitHub Desktop.
Save carousel/403bb0d795e162fe58c3ee997b5f0178 to your computer and use it in GitHub Desktop.
Singleton in PHP
<?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