PHP MVC Add to Array in Post

I have the code below, and whenever I send a value, it does not add it to the array. This is like creating a new array with only the value that I posted.

<?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();

Not quite sure what I'm doing wrong here. Is array_push wrong? I use xampp if that matters. Any ideas what I'm doing wrong?

+4
source share
1 answer

You should understand that every time you submit the form to the user, this is a new execution of your PHP script. So - your array is not the same array from the last time.

, , Session, .

+2

Source: https://habr.com/ru/post/1677621/


All Articles