Access variable in class

2019-03-03 13:28发布

问题:

i would like to access an variable, which is in an class (not as an instance of an class) For example

class myclas
{
private $list=array('1','2','3');
[...]
}

I need to access the values of $list in that way: myclass::$list (witch is'n possible). Is there an alternative way?

Thank you.

//Edit: Thank you all for the answer! Is it possible to use an private variable as values for an public?

class myclas
 {
   private $_list=array('1','2','3');
   public static $staticList=$_list;
  [...]
    }

Right now, i get an error "unexpected T_VARIABLE"

回答1:

class myclas
{
public static $list=array('1','2','3');
}
myClass::$list;


回答2:

See this beautiful guide: http://php.net/manual/en/language.variables.scope.php



回答3:

It's a private variable. If you made it a public static variable you should be able to access it:

class myclas {
 public static $list = array('1','2','3');
}

myclas::$list;


回答4:

It needs to be declared as static.

Example:

class MyClass {

    public static $var = 'foo';
}

Then to access: MyClass::$var;



回答5:

For your edit, see this other beatiful guide about classes and visibility:

http://www.php.net/manual/en/language.oop5.visibility.php