<?php
class Record {
protected static $tableName = 'base';
public static function getTableName() {
echo self::$tableName;
}
}
class User extends Record {
protected static $tableName = 'users';
}
User::getTableName();
It shows: base
Question:
I know I can change the problem by changing this line echo self::$tableName;
to echo static::$tableName;
, it is called 'late static bindings', I read the doc here, but still not quite understand it. So could you give me some explanation on:
a. why this line of code echo self::$tableName;
shows: base?
b. why this line of code echo static::$tableName;
shows: users?
PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. More precisely, late static bindings work by storing the class named in the last "non-forwarding call".
As of PHP 5.3. 0, PHP implements a feature called late static binding which can be used to reference the called class in the context of static inheritance. Late static binding tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. ...
This is called late static binding. This feature of late static binding was introduced in PHP 5.3 and above, previous versions will show a fatal error.
Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time.
The example below will give a minimum example of late static binding:
class A {
static public $name = "A";
static public function getName () {
return self::$name;
}
static public function getNameLateStaticBinding () {
return static::$name;
}
}
class B extends A {
static public $name = "B";
}
// Output: A
echo A::getName(), "\n";
// Output: A
echo B::getName(), "\n";
// Output: B
echo B::getNameLateStaticBinding() , "\n";
B::getName()
outputs the $name
variable from A
since self
is computed from the absolute current class you defined self
in. To solve such cases, use static
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With