PHP OOP - Static Property And  Method

PHP OOP - Static Property And Method

A class property can be declared as static using static keywords.

Remember this important point regarding static property:

  • Static properties are useful when we need a single copy of the property for all the objects.
  • Non-static properties are put inside objects and static properties are put inside the class.
  • Static members(static variable) of a class are independent of any object derived from that class.
  • Note:$this pseudo-variable is not available inside static methods.

How To Create Static Property

To create static properties, just prepend static keyword before the name of the properties or variables. It is used without instantiating (or creating objects from classes). Let us see it with the help of an example.


How To Access Static Property

There are two ways to access static property inside the class name.These are:

  • Within Static Method
  • Outside of the class

Accessing static property inside the static method:

To access static properties inside the static method use, the $self keyword and Scope Resolution Operator (::).

Source Code

Try it now

PHP static property accessing outside of the class:

Static property can be accessed from outside of the class using the class name and can be accessed from outside the class using the class name and Scope Resolution Operator (::). (Only if the visibility is public)

Source Code

Try it now

Basic Difference Between self vs. $this

Followings are the differnces betweeb self and $this keywords.

$this self
$this refers instance of the class or object. It refers class.
It always starts with a dollar sign ($). It does not start with a dollar sign ($)
It is followed by (->) operator. It is followed by :: operator.
Do not place dollar sign ($) after the object operator (->) Use doller sign ($) after the :: operator.