如何在PHP类中定义Array属性

时间:2014-02-22 12:33:40

标签: php arrays function oop

我有以下简单代码,但它在行this->players[] = 'Tom'上产生语法错误:

    <?php

    class club {
            var $clubID = 0;        
            var $players=array();

            function __constructor($clubID = '') {              
                     $this->clubID = $clubID;
            } 

            function populatePlayers() {    
                     $this->players[] = 'Tom';
            }                                           
}

       $myClub = new club(1);
       $myClub->populatePlayers();
       var_dump($myClub->players);
?>

2 个答案:

答案 0 :(得分:4)

应该是

 $this->players[] = 'Tom';

而不是

$this->$players[] = 'Tom';

您需要在$关键字之前添加thisplayers变量不需要。{/ p>

Demo

答案 1 :(得分:0)

试试这个

function populatePlayers() {    
         $this->players[] = 'Tom';
}