PHP5 has added a lot of object-oriented ideas. PHP5's Object-oriented thinking is closer to Java's Object-oriented thinking. Here we will describe the role of static and const in PHP5, hoping to help those who are learning PHP5.
(1) static
The static keyword is in the class, describing a member is static, and static can restrict external access, because the static member belongs to the class and does not belong to any object instance, other classes cannot be accessed. They are shared only to the instance of the class and can be fully protected by the program. Static variables of the class are very similar to global variables and can be shared by all class instances. Static Methods of the class are also the same, similar to global functions. The static method of the class can be used to initialize the static attributes of the class. In addition, static members must use self for access. If this is used, an error occurs.
(2) const
Const is the key word for defining constants. Similar to # define in C, const can define a constant. If its value is changed in the program, an error will occur.
Example: (Note: The following code is from phpe.net)
Class Counter
{
Private static $ count = 0; // defines 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 print
Print (Counter: getCount ()."
N "); // use the direct input class name to access the static method Counter: getCount
// Print the version of the class
Print ("Version useed:". Counter: VERSION ."
N ");
?>