Is instantiation required for function overriding?
Possible Duplicate:
What exactly is late-static binding in PHP?
In this example, PHP will print "NO" rather than "YES", opposite of what I expected.
If I remove static
on function c()
, replace self::
with $this->
and do $e = new B; $e->c();
$e = new B; $e->c();
, things will work.
Does this mean that instantiation is required to make functions in parent classes call overridden functions in inherited classes?
(Side question: Is this a PHP quirk, or does this logic also apply for most other programming languages? If so, what is the rationale behind it?)
class A {
static function c() {
self::d();
}
static function d() {
echo "NO :(n";
}
}
class B extends A {
static function d() {
echo "YES :)n";
}
}
B::c();
You need to use static
keyword instead of self
or $this
.
<?php
class A {
static function c() {
static::d();
}
static function d() {
echo "NO :(n";
}
}
class B extends A {
static function d() {
echo "YES :)n";
}
}
B::c();
// YES :)
This behavior is called Late Static Bindings.
链接地址: http://www.djcxy.com/p/58032.html上一篇: PHP的oo编程父母来实例化孩子
下一篇: 函数重写需要实例吗?