[英]PHP: access static member of class from instance in local class member
I'd like do do this: 我想这样做:
class A {
public static $var = 'foo';
}
class B {
private $a;
public function __construct($a) {
$this->a = $a;
}
public function f() {
echo $this->a::$var; // <---- ERROR
echo get_class($this->a)::$var; // <---- ERROR
// WORKING but awful
$a = $this->a;
echo $a::$var;
}
}
$b = new B(new A());
$b->f();
Note that I don't know if $a
is an instance of A
or another class, I just know that it has a static $var
member. 请注意,我不知道$a
是A
还是另一个类的实例,我只知道它具有静态的$var
成员。 So, unfortunately, I can't use A::$var
inside f
. 因此,不幸的是,我不能在f
内使用A::$var
。
Does anyone know if there is a single-expression syntax to do this, using PHP 5.3+? 有谁知道使用PHP 5.3+是否有单表达式语法来做到这一点?
You're passing an instance of A into B, but $var is a static Member of A which can only be accessed using :: like A::$var. 您正在将A的实例传递给B,但是$ var是A的静态成员,只能使用::来访问A,例如$:。
private function f() {
echo A::$var;
}
EDIT: if you want to make it dependant of the instance stored in $a you could do something like: 编辑:如果要使其依赖于$ a中存储的实例,则可以执行以下操作:
public function f() {
$class = get_class($this->a);
echo $class::$var;
}
First thing I'm seeing is that you couldn't call f() as it is private. 我首先看到的是您无法调用f(),因为它是私有的。
$b->f();
Then maybe you can turn to something like this? 那么也许您可以转向这样的事情?
class B extends A{
private $a;
public function __construct($a) {
$this->a = $a;
}
public function f() {
echo static::$var;
}
}
The following will work but I'd question why you'd want to do this: 以下将起作用,但我想问为什么要这样做:
class A {
public static $var = 'foo';
}
class B {
private $a;
public function __construct($a) {
$this->a = $a;
}
public function f() {
if ($this->a instanceof A) {
echo A::$var;
}
}
}
$b = new B(new A());
$b->f();
you don't need to do anything specifically with $this->a as $var is static to the class. 您不需要使用$ this-> a专门做任何事情,因为$ var对于该类是静态的。
You could write a function like so: 您可以编写如下函数:
function get_static_property($class, $property) {
return $class::$$property;
}
I can't help but wonder why you would need this. 我忍不住想知道为什么您需要这个。 Any reason why you can't have A implement an interface? 为什么没有A实现接口的任何原因? Or use a trait? 还是使用特质? That way you can just echo $this->a->someMethodName()
. 这样,您可以只回显$this->a->someMethodName()
。
PS. PS。 returning strings is generally preferred over echoing inside methods. 返回字符串通常比在内部方法中回显更可取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.