2013-02-23 42 views
-1

我遇到了类内数组的问题。我可以访问它,如果我把它设置为静态的,但我不知道如何修改它,并访问它,如果它不是静态的。如何访问和修改类中的数组?

class Example { 
    protected static $_arr = array(
     "count", 
    ); 

    public static function run($tree) { 
     $_arr[] = "new"; 
     print_r($_arr); 
    } 
} 

如何访问数组,修改它并从公共函数“run”中打印它?

回答

1

$_arr[] = "new";

指的是阵列,这将是您的本地功能。访问您的类的静态变量,你必须使用语法==>self::staticVariableName

你的代码应该是:

class Example { 
protected static $_arr = array(
    "count", 
); 

public static function run($tree) { 
    self::$_arr[] = "new"; 
    print_r(self::$_arr); 
} 
0

我刚刚从@MQuirion的代码所做的一个片段。在这里我写了如何处理你的类中的非静态属性。我希望现在你可以在你的课堂中使用你的数组。

class Example { 
    protected $_arr = array(
     "count", 
    ); 

    public function run($tree) { 
     // print new array + your properties 
     $this -> _arr[] = $tree; 
     //To print only new assigned values without your declared properties 
     $this -> _arr = $tree; 
     print_r($this->_arr); 
    } 
} 
$obj = new Example(); 
$tree = array('a','b','c'); 
$result = $obj->run($tree); 
相关问题