what is the need of late static binding in php

706 Views Asked by At

I have a code in php,

<?php
class DB{
 protected static $table = 'basetable';
 public function Select(){
  echo "Select * from" . static::$table;
 }
}
class Abc extends DB{
 protected static $table = 'abc';
}

$abc = new Abc();
$abc->Select();

from my understanding of late static binding what the above program will return is as follows,

Select * from abc;

and if we dont use late static binding above program will return,

Select * from basetable

because of late static binding the value of $table is substituted in runtime instead of compile time.

But doesn't inheritance give the same output?

since as per the laws of inheritance, the parent attribute is overridden by child attributes

and since $table = abc in child(class Abc), won't it be overridden on $table in parent(Class DB)?

1

There are 1 best solutions below

1
deceze On

static values are looked up differently than $this variables/properties. In the compiler, they're bound early when you use self:

class Foo {
    static $bar = 'baz';

    function test() {
        echo self::$bar;
    }
}

This will always output baz, regardless of whether you extend the class with something else or not. That's where you need late static binding with static instead of self.

Essentially it enables inheritance for static values, which wasn't possible before it existed.