如何访问类的静态成员?
我正在尝试访问类的静态成员。
我的课程是:
class A
{
public static $strName = 'A is my name'
public function xyz()
{
..
}
..
}
//Since I have bunch of classes stored in an array
$x = array('A');
echo $x::$strName;
我在打印时遇到错误。如何打印'A是我的名字'
I am trying to access static member of a class.
my class is:
class A
{
public static $strName = 'A is my name'
public function xyz()
{
..
}
..
}
//Since I have bunch of classes stored in an array
$x = array('A');
echo $x::$strName;
I am getting error while printing. How can I print 'A is my name'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果
A
是一个类,您可以通过A::$strName
直接访问它。更新:
根据数组中的内容,我喜欢将其定义为类对象还是类文字可能是一个因素。我通过以下方式区分这两个术语:
如果您采用类文字方法,然后使用 PHP5.2.8 的
foreach
循环,则在使用 范围解析运算符。所以然后我考虑使用类对象方法,但我实际上可以输出静态变量的唯一方法是使用对象的实例并使用
self
关键字,如下所示,然后在以下情况下调用该方法:迭代,
那么为什么要声明变量
static
呢?它违背了无需实例化对象即可访问变量的整个想法。简而言之,一旦我们获得有关您想要做什么的更多信息,我们就可以继续提供更好的答案。
If
A
is a class, you can access it directly viaA::$strName
.Update:
Depending on what you have inside your array, whether its what I like to define as class objects or class literals could be a factor. I distinguish these two terms by,
If you go the class literals approach, then using a
foreach
loop with PHP5.2.8 I am given a syntax error when using the scope resolution operator.So then I thought about using the class objects approach, but the only way I could actually output the static variable was with an instance of an object and using the
self
keyword like so,And then invoke that method when iterating,
Which at that point why declare the variable
static
at all? It defeats the whole idea of accessing a variable without the need to instantiate an object.In short, once we have more information as to what you would like to do, we can then go on and provide better answers.
如果您想要 PHP5.2 的工作版本,可以使用 reflection 访问类的静态属性。
演示:http://ideone.com/HFJCW
If you want a working version for PHP5.2, you can use reflection to access the static property of a class.
Demo : http://ideone.com/HFJCW
您有一个缺少分号的语法错误,因为它是一个数组,您需要访问索引 0,否则它将尝试调用类“Array”。
应该修复它。
更新
如果你想迭代一个数组来调用一个类变量:
不知道为什么你会想要这样,但就这样了。并且已经过测试,没有抛出任何错误,收到了
A is my name
的有效响应。编辑
显然这仅适用于 PHP 5.3
You have a syntax error with missing semicolon and because it is an array you need to access the index of 0, or else it would be trying to call class 'Array'.
Should fix it.
UPDATE
If you want to iterate over an array to call a class variable:
Not sure why you would want that, but there you go. And this has been tested, no errors were thrown, valid response of
A is my name
was received.EDIT
Apparently this only works under PHP 5.3
从类内部并且想要访问其自己的静态数据成员,您也可以使用
静态::
而不是
自我::
From inside a class and want to access a static data member of its own you can also use
static::
instead of
self::
我确实找到了下一个简单的解决方案,但不知道它是否好。
我的解决方案是:
I do find next one simple solution but don't know whether its good one or not.
My soln is: