Home > Article > Backend Development > Understanding the Static and Const keywords in PHP5_PHP Tutorial
A lot of object-oriented ideas have been added to PHP5. The object-oriented ideas of PHP5 are closer to the object-oriented ideas of Java. Here we will describe the functions of static and const keywords in PHP5, hoping to be helpful to friends who are learning PHP5.
(1) static
The static keyword in a class is used to describe a member as static. Static can restrict external access, because the members after static belong to the class and do not belong to any object instance. They are inaccessible to other classes and are only accessible to the class. Instance sharing can ensure that the program fully protects the members. Static variables of a class are very similar to global variables and can be shared by all instances of the class. The same is true for static methods of a class, similar to global functions. Static methods of a class can access static properties of the class. In addition, static members must be accessed using self. Using this will cause an error.
(2)const
const is a keyword that defines a constant, similar to #define in C. You can define a constant. If its value is changed in the program, an error will occur.
Give an example of the above code: (Note: The following code comes from phpe.net)
class Counter
{
private static $count = 0;//Define a static attribute
const VERSION = 2.0; //Define a constant
//Constructor
function __construct()
{
self::$count ;
}
//Destructor
function __destruct()
{
self::$count--;
}
//Define a static method
static function getCount()
{
return self::$count;
}
}
//Create an instance
$c = new Counter();
//Execute printing
print( Counter::getCount(). "
n" ); //Use direct input of class name to access static method Counter::getCount
//Print class version
print( "Version used: " .Counter::VERSION. "
n" );
?>