Accessing Static Variable from child->child class php
I have the following setup:
<?php
class core {
static $var1;
}
class parent extends core {
f开发者_如何学编程unction getStatic() {
return parent::$var1;
}
}
class child extends parent {
function getStatic() {
// I want to access core static var, how can i do it?
//return parent::$var1;
}
}
?>
I need to be able to use parent::$var1 but from within class child.. is this possible? Am I missing something?
Just reference it as self... PHP will automatically go up the chain of inheritance until it finds a match
class core {
protected static $var1 = 'foo';
}
class foo extends core {
public static function getStatic() {
return self::$var1;
}
}
class bar extends foo {
public static function getStatic() {
return self::$var1;
}
}
Now, there will be an issue if you don't declare getStatic in bar. Let's take an example:
class foo1 extends core {
protected static $var1 = 'bar';
public static function getStatic() {
return self::$var1;
}
}
class bar1 extends foo1 {
protected static $var1 = 'baz';
}
Now, you'd expect foo1::getStatic()
to return bar
(and it will). But what will Bar1::getStatic()
return? It'll return bar
as well. This is called late static binding. If you want it to return baz
, you need to use static::$var1
instead of self::$var1
(PHP 5.3+ only)...
core::$var1 seems best for your needs...
The biggest problem here is that you're using the keyword parent as a class name. This makes it completely ambiguous whether your calls to parent::$var1 are intended to point to that class, or to the parent of the calling class.
I believe, if you clean this up, you can achieve what you want. This code prints 'something', for example.
class core {
static $var1 = 'something';
}
class foo extends core {
function getStatic() {
return parent::$var1;
}
}
class bar extends foo {
function getStatic() {
// I want to access core static var, how can i do it?
return parent::$var1;
}
}
$b = new bar ();
echo $b->getStatic ();
It also works if you use core::
instead of parent::
. Those two will behave differently, though, if you declare a static $var1 inside of the foo
class as well. As is it's a single, inherited variable.
精彩评论