Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 scope ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page