PHP MVC在帖子上添加到数组

我有下面的代码,每当我发布一个值时,它都不会将它添加到数组中.这就像它创建一个只有我发布的值的新数组.

<?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.我有什么想法我做错了吗?

最佳答案 您必须了解每次用户提交表单时 – 都是php脚本的新执行.

所以 – 你的数组 – 与上次不一样.

要做你想做的事 – 你可以使用Session.

点赞