Skip to content

Instantly share code, notes, and snippets.

@junaidtk
Last active January 23, 2019 09:33
Show Gist options
  • Save junaidtk/c7517dcc193acedc631b9d23d012be0d to your computer and use it in GitHub Desktop.
Save junaidtk/c7517dcc193acedc631b9d23d012be0d to your computer and use it in GitHub Desktop.
Static methods and properties in PHP OOP
Static means they are unchanging.
static function means, it is a function namespaced by the name of its class.
To make a function static, we need to add the key work static in the function definition.
Like
public static function(){
// Statement.
}
We can call a static method without intanstiating the object. you can use below code for calling the static method.
classname::function name();
Unlike a method in a class, the static methods are just like php function, we can access the function from any where.
The class name just behaves little more than "namespace" or "container".
To access the static method inside from a class is by using key word self.
self::staticMethodname();
But in PHP the use of static methods and properties are discouraged. They are "genearl state" every one in the sysytem can use.
so it is hard to control what is happening.
You can use the static methods and properties which is realy static (Unchanged).
Singletone is way to force class to have one instance.
<?php
class Singleton {
// Unique instance.
private static $instance = null;
// Private constructor prevent you from instancing the class with "new".
private function __construct() {
}
// Method to get the unique instance.
public static function getInstance() {
// Create the instance if it does not exist.
if (!isset(self::$instance)) {
self::$instance = new Singleton();
}
// Return the unique instance.
return self::$instance;
}
}
This is a better way, here we can use inheritance, interfaces, This method is calling instantiated object.
But if you have 2 or more instance with diffrent input property (connection to two diffrent databases),
you can't use singletone behaviour.
whenever you use static, be sure to use it for utilities and not for convenience reasons.
Beacuse the static can be accessed from anywhere in the system.
Reference : https://wpshout.com/courses/object-oriented-php-for-wordpress-developers/php-static-methods-in-depth/
https://stackoverflow.com/questions/33705976/when-should-i-use-static-methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment