Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

php - How do I access static member of a class?

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'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 ';'
}

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();
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...