PHP MVC 在提交时添加到数组

4
我有以下的代码,每次我提交一个值时,它并没有将它添加到数组中。就好像它创建了一个只包含我提交的值的新数组。
<?php

class Model
{
    public $task;

    public function __construct()
    {
        $this->task = array();
    }
}

class Controller
{
    public $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    public function addTask($taskToAdd)
    {
        array_push( $this->model->task, $taskToAdd);
    }
}

class View
{
    public $model;
    public $controller;

    public function __construct(Controller $controller, Model $model)
    {
        $this->controller = $controller;
        $this->model = $model;
    }

    public function drawScreen()
    {
        $htmlForm = "<!doctype HTML>";
        $htmlForm = $htmlForm . "<html><head><title>php form test</title></head>";
        $htmlForm = $htmlForm . "<body>";
        $htmlForm = $htmlForm . "<form method='POST' action='index.php'>";
        $htmlForm = $htmlForm . "<input type='text' name='newtask' />";
        $htmlForm = $htmlForm . "<input type='submit' value='Add new task' />";
        $htmlForm = $htmlForm . "</form></body></html>";

        echo $htmlForm;
    }

    public function listTasks()
    {
        print_r($this->model->task);
    }
}

    $model = new Model();

    $controller = new Controller($model);

    $view = new View($controller, $model);

if (isset($_POST['newtask'])) {
    $taskToAdd = $_POST['newtask'];
    $controller->addTask($taskToAdd);
}

echo $view->drawScreen();
echo $view->listTasks();

我不确定我在这里做错了什么。array_push不是正确的方式吗?我正在使用xampp,如果有区别的话。你有什么想法,我做错了什么?


1
你必须将模型保存到数据库中,并每次从数据库中加载它。因为你的PHP代码会一遍又一遍地编译脚本,每次都会破坏你的模型。试着像计算机一样思考,如果你得到这些指令,你会怎么做? - Black
1个回答

2
你需要明白,每一次用户提交表单都会执行你的php脚本,所以你的数组不是上一次的相同数组。
要实现你想要的功能,可以使用例如Session的方法。

好的,我明白了。就像在 .net 中的状态一样。 - Unseen
我不确定你的代码目标是什么,但你也可以在JavaScript中建立一个数组的数组,然后在某个时候将所有这些数组发送到PHP进行处理。 - abetwothree

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接