0

Я создал класс формы

class Form {
    private $type ;
    private $value;
    private $placeholder;
    private $action = '';
    private $method;
    private $name;
    private $className;

    public function checkValue($arr) {
        if (array_key_exists('value', $arr)) {
            $this->value = $arr['value'];
        }
    }

    public function checkName($arr) {
        if (array_key_exists('name', $arr)) {
            $this->name = 'name="'.$arr['name'].'"';
        }
    }

    public function checkClass($arr) {
        if (array_key_exists('class', $arr)) {
            $this->className = 'class="' . $arr['class'] . "\" ";
        }
    }

    public function input($arr) {
        $this->type = $arr['type'];
        $this->checkName($arr);
        $this->checkValue($arr);
        $this->checkClass($arr);
        return '<input ' . $this->className . $this->name . ' type="' .$this->type . '" value="' .$this->value . '">';
    }

    public function password($arr) {
        $this->type = 'password';
        $this->checkName($arr);
        $this->checkValue($arr);
        $this->checkClass($arr);

        return '<input '. $this->className . $this->name .' type="' .$this->type . '" value="' .$this->value . '">';
    }

    public function submit($arr) {
        $this->type = 'submit';
        $this->checkName($arr);
        $this->checkValue($arr);
        $this->checkClass($arr);
        return '<input ' . $this->className . $this->name .' type="' .$this->type . '" value="' .$this->value . '">';
    }

    public function textarea($arr) {
        $this->placeholder = $arr['placeholder'];
        $this->name = $arr['name'];
        $this->checkValue($arr);
        $this->checkClass($arr);
        return '<textarea ' . $this->className . $this->name . ' placeholder="' . $this->placeholder. '">' . $this->value . '</textarea>';
    }

    public function open($arr) {
        $this->action = $arr['action'];
        $this->method = $arr['method'];
        $this->checkClass($arr);
        return '<form '.$this->className.' action="'.$this->action.'" method="'.$this->method.'">';
    }

    public function close() {
        return '</form>';
    }
}

Потом создал класс, который всё наследует от класса Form и почему, если после отправки, не сохраняется значение в input name?

class SmartForm extends Form {
    public function checkValue($arr) {
        if (!empty($_POST['name'])) {
            $this -> value = $_POST['name'];
        }
        parent::checkValue ($arr);
    }
}

$form2 = new SmartForm;

echo $form2->open(['action' = > './2.php', 'method' =>'POST']) ."\n";
echo "\t ".$form2->input(['type' = > 'text', 'placeholder' =>'Ваше имя', 'name' =>'name', 'class' =>'name']) .
"\n";
echo "\t ".$form2->password(['placeholder' = > 'Ваш пароль', 'name' =>'pass', 'class' =>'user-password']) ."\n";
echo "\t ".$form2->submit(['value' = > 'Отправить']) ."\n";
echo $form2->close();
5
  • Что значит не сохраняется? В БД, в html на сайте?
    – DaemonHK
    29 ноя 2017 в 3:27
  • про бд ничего не говорил
    – DivMan
    29 ноя 2017 в 6:24
  • Тогда уточните, не сохраняется св-во name или значение в value?
    – DaemonHK
    29 ноя 2017 в 6:27
  • value в форму не подставляется
    – DivMan
    29 ноя 2017 в 7:38
  • Если вкратце: value=<?php echo isset($_POST['field'])?$_POST['field']:''; ?> добавьте проверку в ваш метод checkValue
    – DaemonHK
    29 ноя 2017 в 8:29

1 ответ 1

1

PHP скрипт выводит форму и завершается. При этом все классы и переменные уничножаются. Чтобы после отправки формы у вас запускается новая копия скрипта и она нечего не знает о прошлом скрипте.

У вас в классе наследнике есть метод checkValue который как раз получает из значений формы массив $_POST значение поля name это надо сделать в скрипте 2.php

$form2 = new SmartForm();
$form2->checkValue([]);

После этого у вас в свойстве класса value будет значение введенное пользователем в соответствующий инпут.

Вообще класс построен не совсем верно так как описывает одно поле, а у вас как минимум 2 выводится.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.