reference访问静态变量

reference访问静态变量

本文介绍了通过$ var :: $ reference访问静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用变量类名来访问类中的静态变量.我知道,要访问该类中的 function ,您可以使用call_user_func():

I am trying to access a static variable within a class by using a variable class name. I'm aware that in order to access a function within the class, you use call_user_func():

class foo {
    function bar() { echo 'hi'; }
}
$class = 'foo';
call_user_func(array($class, 'bar')); // prints hi

但是,当尝试访问该类中的静态变量时,此方法不起作用:

However, this does not work when trying to access a static variable within the class:

class foo {
    public static $bar = 'hi';
}
$class = "foo";
call_user_func(array($class, 'bar')); // nothing
echo $foo::$bar; // invalid

如何获取此变量?可能吗?我有一种不好的感觉,即此功能仅在以后的PHP 5.3中可用,而我正在运行PHP 5.2.6.

How do I get at this variable? Is it even possible? I have a bad feeling this is only available in PHP 5.3 going forward and I'm running PHP 5.2.6.

推荐答案

您可以使用 reflection 做到这一点.给定类名,创建一个 ReflectionClass 对象,然后使用getStaticPropertyValue方法获取静态变量值.

You can use reflection to do this. Create a ReflectionClass object given the classname, and then use the getStaticPropertyValue method to get the static variable value.

class Demo
{
    public static $foo = 42;
}

$class = new ReflectionClass('Demo');
$value=$class->getStaticPropertyValue('foo');
var_dump($value);

这篇关于通过$ var :: $ reference访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:39