DEV Community

spO0q πŸ’
spO0q πŸ’

Posted on • Edited on

Binding in PHP

Understanding binding in PHP is essential for anyone that wants to use this unique language.

Late Static Binding (LSB) is the combination of Late binding and Static binding, two different concepts.

Static?

You make static calls when you don't need any object creation. You can read this post if you need more details :

It's not rare to use static calls, even when a class inherits from its parent class. You may need some features that won't vary.

Static binding

Sometimes, people refer to static binding with another term: early binding.

Static binding happens when you use the scope resolution operator ::.

When inheriting from a mother class in your child class, there's a counter-intuitive behavior (maybe not ^^):

<?php

class MotherClass {
    protected static $cat = "generation A";

    public static function displayCat() {
        echo self::$cat;
    }
}

class ChildClass extends MotherClass {
    protected static $cat = "generation B";
}

ChildClass::displayCat();// displays "generation A"
Enter fullscreen mode Exit fullscreen mode

As the displayCat() method is defined in the parent class, you'll get the parent stuff even if you call it with the child class.

PHP resolves it using the class in which the method belongs.

Late binding

Sometimes, people refer to late binding with another term: dynamic binding.

Unlike early binding (static binding), PHP will bind things at runtime. It needs an object creation :

<?php

class MotherClass {
    protected $cat = "generation A";

    public function displayCat() {
        echo $this->cat;
    }
}


class ChildClass extends MotherClass {
    protected $cat = "generation B";
}

$child = new ChildClass();
$child->displayCat();//displays "generation B"
Enter fullscreen mode Exit fullscreen mode

This time we get "generation B" as probably intended.

Late static binding

If you want to redefine static stuff (~ override output) in the child class, use the keyword static.

The PHP interpreter will leave it for runtime. It's like a pending status:

<?php

class MotherClass {
    protected static $cat = "generation A";

    public static function displayCat() {
        echo static::$cat;
    }
}


class ChildClass extends MotherClass {
    protected static $cat = "generation B";
}

ChildClass::displayCat();// displays "generation B"
Enter fullscreen mode Exit fullscreen mode

This time, we also get "generation B" as probably intended.

Wrap up

I hope you know more about binding in PHP, especially late static binding, thanks to this short article.

This technique has been available since PHP 5.3. It makes the use of static methods and variables less risky for inheritance thanks to a simple keyword.

Top comments (0)