PHP:包含赞助商数组的类和用于回显它们的方法

时间:2017-11-16 16:51:42

标签: php arrays variables foreach

我希望我的Datasource_Sponsor类包含赞助商信息,一个名为sponsorList的数组和一个回应每个赞助商的方法。

目前我有这个

class Datasource_Sponsor
 {

protected $sponsor = 'New and Upcoming Startup';
protected $sponsor2 = 'Average Company Ltd.';
protected $sponsor3 = 'Super Duper Cool Best Company Ever';


protected $sponsorList = array($sponsor, $sponsor2, $sponsor3);

public function returnSponsors()
{
    foreach ($sponsorList as $sponsor) {
        $sponsor = new Sponsor();
        echo 'Sponsor: ' . $sponsor->getSponsor() . '<br/>';
        echo '<hr>';
        }

    }
}

我收到此错误“致命错误:常量表达式包含此行的无效操作”

protected $sponsorList = array($sponsor, $sponsor2, $sponsor3);

1 个答案:

答案 0 :(得分:1)

你不能以这种方式使用属性,我建议你这样做:

<?php
class Datasource_Sponsor
 {

    protected $sponsor = 'New and Upcoming Startup';
    protected $sponsor2 = 'Average Company Ltd.';
    protected $sponsor3 = 'Super Duper Cool Best Company Ever';

    protected $sponsorList;

    public function __construct(){
        $this->sponsorList = [$this->sponsor, $this->sponsor2, $this->sponsor3];
    }

    public function returnSponsors()
    {
        foreach ($this->sponsorList as $sponsor) {
            $myOthersponsor = new Sponsor();
            echo 'Sponsor: ' . $myOthersponsor->getSponsor() . '<br/>';
            echo '<hr>';
        }

    }

}