【问题标题】:How to define an Array property in a PHP class [closed]如何在 PHP 类中定义数组属性 [关闭]
【发布时间】:2014-03-24 03:30:02
【问题描述】:

我有以下简单代码,但它在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);
?>

【问题讨论】:

  • @Akshay,编辑时请小心!你给代码引入了一个之前不存在的问题,现在大部分答案都失效了!

标签: php arrays function oop


【解决方案1】:

应该是

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

而不是

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

您需要在this 关键字之前添加$,而players 变量不需要。

Demo

【讨论】:

  • 即使这样也会给出运行时错误:
  • @AmanKhanna,我不这么认为.. 看到这个eval.in/104496
  • 原始问题没有$。这是一个编辑器错误。
  • @Qantas , 投反对票的原因是什么?
【解决方案2】:

试试这个

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

【讨论】:

  • 您不需要在players 之前添加$,因为这会导致FATAL 错误。
猜你喜欢
  • 2013-10-30
  • 2022-12-14
  • 2012-04-14
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
相关资源
最近更新 更多