PHP简单面向对象的应用程序

时间:2014-05-27 07:23:47

标签: php class oop instance-variables

我在这个程序的最后一行得到了句点的未定义变量和subPeriods。不确定是什么问题。可能是我的实例吗?

这是我在PHP中首次正确尝试oop,所以我确信我做错了。

$global_periods = 5;
$global_subperiods = 2;

$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");

class User {
    public $userId;
    public $periods = array();

    public function __construct($number)
    {
        $this->userId = $number;
    }

    public function addPeriod($pno)
    {
        $periods[] = new Period($pno);
    }
}

class Period {
    public $periodNo;
    public $subPeriods = array();

    public function __construct($number)
    {
        $this->periodNo = $number;
    }

    public function addSubPeriod($spno)
    {
        $subPeriods[] = new SubPeriod($spno);
    }
}

class SubPeriod {
    public $SubPeriodNo;
    public $answers = array();

    public function __construct($number)
    {
        $this->SubPeriodNo = $number;
    }

    public function addAnswer($answer)
    {
        $answers[] = new Answer($answer);
    }
}

class Question {
    public $answer;

    public function __construct($ans)
    {
        $this->answer = $ans;
    }

    public function getAnswer()
    {
        echo $answer;   
    }
}        

$userlist = array();

$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result))
{
    $userlist[] = new User($row['user_ref']);
}

for ($i = 0; $i >= count($userlist); $i++)
{
    for ($x = 1; $x > $global_periods; $x++)
    {
        $userlist[i]->addPeriod($x);

        for ($y = 1; $y > $global_subperiods; $y++)
        {
            $userlist[i]->$periods[x]->addSubPeriod($y);

            foreach($questionslist as $aquestion)
            {
                $sql = 'SELECT ' . $questionNumber . ' FROM _survey_1_as WHERE user_ref = ' .
                     $i . ' AND answer_sub_period = ' . $y . ' AND answer_period = ' . $x .''; 

                $result = mysql_query($sql);

                while ($row = mysql_fetch_array($result))
                {
                    $userlist[i]->$periods[x]->$subPeriods[y]->addAnswer($row[$questionNumber]);
                }
            }
        }
    }   
}

$userlist[3]->$periods[2]->$subPeriods[2]->getAnswer();

1 个答案:

答案 0 :(得分:1)

删除$ userlist后面的所有$符号,您只需要定义第一个变量。您不能使用这样的美元符号,这样,它会尝试获取$符号后面的单词的值并调用它,但该变量不存在。

相关问题