Section 8.15. Static Class Methods and Properties


8.15. Static Class Methods and Properties

You can declare methods and properties from a class as static , meaning that they are available to the class as well as to individual objects. For example, if we wanted to define a function, nextID( ), that returned the next available employee ID, we could declare it static. That way, we could call nextID( ) directly from the script without the need for any Employee objects. This allows you to use a helpful class method without needing to instantiate an object first.

You can also make properties static, which results in there being only one of that property for the entire classall objects share that one property. So, rather than using the nextID( ), we could just have a static property $NextID that holds the next available employee ID number. When we create a new employee, it takes $NextID for its own $ID, then increments it by one.

To declare your properties and methods as being static, use the static keyword. Here is an example:

     class Employee {             static public $NextID = 1;             public $ID;             public function _ _construct( ) {                     $this->ID = self::$NextID++;             }             public function NextID( ) {                     return self::$NextID;             }     }     $bob = new Employee;     $jan = new Employee;     $simon = new Employee;     print $bob->ID . "\n";     print $jan->ID . "\n";     print $simon->ID . "\n";     print Employee::$NextID . "\n";     print Employee::NextID( ) . "\n"; 

That will output 1 2 3 4, which are the employee IDs of Bob, Jan, and Simon, respectively, as well as the next available ID number, 4. Note that the scope resolution operator, ::, is used to read the static property from the Employee class.

The use of self inside the constructor refers to the class of the current object, just as earlier on we used parent to refer to the parent class of the current object.

There are some additional special rules to using static methods and properties. First, because static method calls are actually resolved at compile time, you may not use the contents of a variable as the class name, like this:

     $foo = "Employee";     print $foo::$NextID;     // will not work 

You cannot access static class variables from objects of that class outside of their methods, which means "$bob->NextID" will not work. You may, however, access static class methods as you would access any other method.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net