1. First aproach: static and self

Let distinguish the difference between static and self in PHP. The simple difinition is: while self referring to the class within which you use the keyword, static performs Late Static Binding and thus it binds the variable value from child class. Imagine we have a class like this:

class Car
{
    public static function model()
    {
         self::getModel();
    }

    protected static function getModel()
    {
        echo "I am a Car!";
    }
}
Car::model();
// I am a Car!

Now create class BMW that extends the Car class

class BMW extends Car
{
   protected static function getModel()
   {
       echo "I am a BMW!";
   }
}
BMW::model()
// I am a Car!

We are expecting to see I am a BMW!, but sefl key word will refer to the class that you use it, meaning the Car class.

The solution here is applying late static binding:

class Car
{
    public static function model()
    {
         static::getModel();
    }

    protected static function getModel()
    {
        echo "I am a Car!";
    }
}
BMW::model()
// I am a BMW!

What happened? you can clearly see that the static keyword refers to the class call it, and getModel() method of class BMW will be called, instead of the Car one. This feature is very helpful, Image you have a hundred brands of cars, extend the Car class, and you may want to have a method in Car to handle the property that will be only declared on the child Class.

2. Real World – late static binding

Ok, we have Ford brand like this

class Car
{
    public function sale()
    {
	    echo "the car brand". "is sale off 20%";
    }
}

class BMW extends Car
{
    public function sale()
    {
	    echo "BMW". "is sale off 20%";
    }
}

class Ford extends Car
{
    public function sale()
    {
	    echo "Ford ". "is sale off 20%";
    }
}
$ford = new Ford();
$ford->sale();
// Ford is sale off 20%

$bmw = new BMW();
$bmw->sale();
// BMW is sale off 20%

Both Ford and BMW class have sale() method, duplicated code!. Instead, we could use Late static binding:

class Car
{
    public function sale()
    {
	    echo static::$brandName. " is sale off 20%";
    }
}

class BMW extends Car
{
    protected static $brandName = 'BMW';
}

class Ford extends Car
{
    protected static $brandName = 'Ford';
}

Now, the result will be the same, and your code looks much better!

$ford = new Ford();
$ford->sale();
// Ford is sale off 20%

Car class now execute sale() method, but the $brandName is defined in child class. That’s the point!


One thought on “Late static binding in PHP – write code as a senior developer

Leave a Reply

Your email address will not be published.