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:
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;
}
There are two ways to access static property inside the class name. These are:
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();
}
}
?>
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();
?>
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.
|