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 class—all 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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.