Sorry, this video is only available to Pro accounts.

Upgrade your account to get access to all content.

The PHP Singleton Class

Created on March 3rd, 2018

In this video we will show you how to create a PHP singleton class and why you may want to use it. We'll show you how to create a basic class and a similar implementation with a singleton class.

A Singleton class is instantiated by itself and does not have multiple instances like a normal class.

You can find the source code to the video here: https://github.com/thedevdojo/create-a-php-singleton-class

You can take a look at each of the singletons created in this video below:

Greeting.php (singleton)

<?php

class Greeting{

	private static $instance;
	public static $name;

	public static function singleton(){

		if( !isset(self::$instance) ){
			self::$instance = new Greeting;
		}

		return self::$instance;

	}

	public static function setname($name){
		self::$name = $name;
	}

	public static function greet(){
		return 'Hello ' . self::$name . ' from the Singleton Greeting Class';
	}

}

Calculator.php (singleton)

<?php

class Calculator{

	private static $instance;

	public static function singleton(){

		if( !isset(self::$instance) ){
			self::$instance = new Greeting;
		}

		return self::$instance;

	}

	public static function add($num1, $num2){
		return (int)$num1 + (int)$num2;
	}

}

Comments (0)