The Difference and Introduction of PHP Static Method Static Attribute and Constant Attribute

  • 2021-12-04 18:23:39
  • OfStack

If static keyword is used to modify attributes and methods in PHP, these attributes and methods are called static attributes and static methods. The static keyword states that a property or method is related to a class, not to a specific instance of the class, so such a property or method is also called a "class property" or a "class method."

Why use static methods and properties in your program? They have several features that are useful: You don't need to instantiate the class to access static methods and properties, and you can use them anywhere in your code!


<?php
class Example{
 static public $num = 0;
 static public function staticFunc(){
 self::$num++;
 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. You can't use pseudo keywords in static methods

So what is the difference between constant attributes and static attributes?


<?php
class Example{
  const NUM = 0;
  //...
}
?>

Constant properties do not start with $but are named in uppercase letters. They differ from static properties in that they cannot be copied again or parsed incorrectly.

Constant attribute

Some attributes can't be changed

In PHP 5, you can define a constant attribute in a class, like global variable 1, and the class constant 1 cannot be changed once it is set. Constant attributes are declared with the const keyword. Constants don't start with $like regular attributes. By convention, constants can only be named in uppercase letters, as follows:


class shopProduct {
    constAVAILABLE = 0;
    // … 
}

Constant properties contain only values of basic data types. You cannot assign 1 object to a constant. Like static property 1, constant properties can only be accessed through classes, not through instances of classes. There is no need to use $as a preamble when referring to constants, as follows:


echoshopProduct::AVAILABLE;

Assigning a value to an already declared constant causes a parsing error.

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

Summarize


Related articles: