6.15 Static dataThis is NOT the latest copy of this book; click here for the latest version.
There is one other special thing you can do with OOP in PHP that I have left till last because it is a little hard to get your head around. Put simply, you can declare functions and variables from a class as "static", meaning that they are always available.
For example, if we wanted our bark() function to be called as if it were a normal function, we could declare it static. That way, we could call bark() directly from the script without the need for any dog objects. This might sound counter-intuitive at first, but it is actually helpful as it allows you to make use of a particularly helpful function without needing to instantiate an object first.
You can also make class variables static, which results in there being only one of that variable for the entire class - all objects share that one variable. So, if we wanted to have an object for every employee in a business, we might have a static variable $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 variables and functions as being static, use the "static" keyword. Here is an example:
<?php
class employee {
static public $NextID = 1;
public $ID;
public function __construct() {
$this->ID = 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"; ?>
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 variable from the employee class.
Also of note is the use of "self" inside the constructor - this 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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|