Learn PHP Tutorial

PHP OOP – Static Methods and Properties


Since methods and properties are bound to an instance of a class. And methods and properties can be used only after the creating object of a class. But here static methods and properties comes which allow us to access the methods and properties in the context of a class rather than an object. And these type of methods and properties are called Class methods and class properties.

These class methods and class properties are called static methods and static properties.

A static class (with only static functions) prevents you to use many OOPs features like Inheritance, Interface implementation.

Static Method

To define a static method, you need to put static keyword before the function name.

Syntax:

class My_class
{
	public static function method_name(arguments)
	{
		//Your code here...
	}
}

How to call a static method from the inside of the class

Using a special variable ‘self’, you can call a static method inside a class.

self::method_name(arguments);

How to call a static method from the outside of the class

My_class::method_name(arguments);

Static properties

To define a static property, you need to put static keyword before the property name.

class My_class
{
	public static $property_name;

	public static function method_name(arguments)
	{
		//Your code here...
	}
}

How to call a static property from the inside of the class

self::property_name

How to call a static property from the outside of the class

MyClass::$property_name;