PHP Static Method

PHP OOP - static property is created by just prepending the static keyword before the name of the properties or variables of the class while PHP static method is declared with the static keyword.

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.

    
 class Fruit{
	public static $fruitName;
}
   

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

          <?php
class Fruits {
public static function basicInfo() {
	echo "Ok!! I will provide you information about upcoming new fruit in the market.";
}
public function __construct() {
	self::basicInfo();
}
}
?>
        
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

          <?php
class Fruits {
public static function basicInfo() {
echo "Ok!! I will provide you information about upcoming new fruit in the market.";
}
public function __construct() {
	self::basicInfo();
}
}
Fruits::basicInfo();

?>
        
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.

Web Tutorials

PHP Static Method
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4