如何访问类的静态成员? [英] How do I access static member of a class?

查看:294
本文介绍了如何访问类的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试访问类的静态成员。

I am trying to access static member of a class.

我的类是:

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 getting error while printing. How can I print 'A is my name'

推荐答案

如果 A 是一个类,您可以通过 A :: $ strName 直接访问它。

If A is a class, you can access it directly via A::$strName.

class A {
    public static $strName = 'A is my name';
}

echo A::$strName; // outputs "A is my name"



更新:



根据数组中的内容,我喜欢定义为类对象还是类文字,这可能是一个因素。我用这两个术语来区分这两个术语:

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,

$objClasses = array(new A(), new B()); // class objects
$myClasses = array('A','B');           // class literals

如果你使用类文字方法,那么使用 foreach 使用PHP5.2.8循环我使用范围解析操作符

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.

foreach ($myClasses as $class) {
     echo $class::$strName;
  //syntax error, unexpected '::', expecting ',' or ';'
}

所以我想到了使用类对象方法,但是我可以实际输出静态变量的唯一方法是一个对象的实例,并使用 self 关键字如此,

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,

class A {
    public static $strName = 'A is my name';

    function getStatic() {
        return self::$strName;
    }
}

class B {
    public static $strName = 'B is my name';

    function getStatic() {
        return self::$strName;
    }
}

然后在迭代时调用该方法,

And then invoke that method when iterating,

foreach($objClasses as $obj) {
    echo $obj->getStatic();
}

那么为什么声明变量 static ?它破坏了访问一个变量而不需要实例化一个对象的整个想法。

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.

这篇关于如何访问类的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆