1

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)?

pgSystemTester
  • 8,979
  • 2
  • 23
  • 49
mach2
  • 450
  • 2
  • 6
  • 24
  • Well, have you tried the same thing with `self::$table`…? – deceze Jun 18 '18 at 14:14
  • 1
    `static` properties are not inherited because they are, in fact, global variables with fancy names and (optional) limited visibility. – axiac Jun 18 '18 at 14:18

1 Answers1

0

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Hi @deceze + 1, So, will late static binding look in the calling class first and if it doesn't find it look in the parent class? –  Feb 03 '23 at 11:32