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

4

1 回答 1

0

static值的查找方式与$this变量/属性的查找方式不同。在编译器中,当您使用它们时,它们会提前绑定self

class Foo {
    static $bar = 'baz';

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

这将始终输出baz,无论您extend的班级是否有其他内容。这就是您需要后期静态绑定static不是self.

从本质上讲,它支持static值的继承,这在它存在之前是不可能的。

于 2018-06-18T14:17:25.923 回答