Difference and introduction of PHP static method, static property and constant property


If static keyword is used to modify properties and methods in PHP, these properties and methods are called static properties and static methods. Static keyword declares that a property or method is related to a class, rather than a specific instance of the class. Therefore, such a property or method is also known as “class property” or “class method”.

Why use static methods and properties in programs? They have several features that are useful: static methods and properties can be accessed without instantiating classes, and can be used anywhere in the code!

class Example{
 static public $num = 0;
 static public function staticFunc(){
 print self::$num;
echo Example::$num;
echo Example::staticFunc();

It should be noted that:

1. Static methods cannot access ordinary properties, only static properties

2. Static methods are class scoped, so you can use:: to connect static properties and static methods without instantiation

3. Pseudo keywords cannot be used in static methods

So what’s the difference between a constant property and a static property?

class Example{
  const NUM = 0;

The constant property does not start with $but is named with an uppercase letter. The difference between the constant property and the static property is that it cannot be copied again, otherwise it will parse incorrectly.

Const Attribute

Some attributes cannot be changed

In PHP 5, constant properties can be defined in classes. Like global variables, class constants cannot be changed once they are set. Constant properties are declared with the const keyword. Constants do not start with $as regular properties do. By convention, constants can only be named in uppercase letters, as follows:

class shopProduct {
    constAVAILABLE = 0;

Constant properties contain only values of the base data type. An object cannot be assigned to a constant. Like static properties, constant properties can only be accessed through a class, not through an instance of the class. You do not need to use $as a leader when referencing constants, as follows:


Assigning a value to a declared constant causes parsing errors.

Constants should be used when a property needs to be accessible in all instances of the class and the value of the property does not need to be changed.


The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer. If you want to know more about it, please check the relevant links below