Static data

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:

    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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Helpful utility functions >>

Previous chapter: __toString()

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.