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 the static and const keywords in PHP5, and hope it will be helpful for friends who want to learn 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.
(For the similarities and differences between this and self, see: http://blog.csdn.net/heiyeshuwu/archive/2004/11/03/165828.aspx)
(2) const
Const is a key word that defines 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)
Copy codeThe Code is as follows:
<? Php
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 (). "<br> n"); // you can directly enter a class name to access the static method Counter: getCount.
// Print the version of the class
Print ("Version useed:". Counter: VERSION. "<br> n ");
?>
Well, the things I know in my heart are clearly explained here, but I don't think I understand static. Please give me some advice!