How do I access static member of a class?

后端 未结 5 582
北海茫月
北海茫月 2020-12-03 09:48

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()
    {
         


        
5条回答
  •  青春惊慌失措
    2020-12-03 10:25

    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'.

    class A
    {
        public static $strName = 'A is my name';
    
        public function xyz()
        {
            // left blank and removed syntax error
        }
    }
    $x = array('A');
    echo $x[0]::$strName;
    

    Should fix it.

    UPDATE

    If you want to iterate over an array to call a class variable:

    $x = array('A', 'B');
    foreach ($x as $class) {
         echo $class::$strName;
    }
    

    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

提交回复
热议问题