简体   繁体   English

表单输入到类属性

[英]Form inputs to class properties

I'm trying to learn OO PHP and I'm working on a contents manager project, I want to construct an object starting from an html form. 我正在尝试学习OO PHP,并且正在从事内容管理器项目,我想从html表单开始构造一个对象。

For example, if I have a form with ten textbox (or other types of input), I sent the form in POST mode, then I want to construct my object starting from POST data. 例如,如果我有一个包含十个文本框的表单(或其他类型的输入),则以POST模式发送该表单,那么我想从POST数据开始构建对象。

Do I have to pass them as constructor's parameters, or as an array? 我是否必须将它们作为构造函数的参数或数组传递? How? 怎么样?

Just an example: 只是一个例子:

My little form: Name, Surname, Description (but there might be over ten inputs) 我的小表格:名称,姓氏,描述(但可能有十多个输入)

My $_POST array: ('name'=>'Mario', 'surname'=>'Rossi', 'description'=>'Just a description here.') 我的$ _POST数组:(“名称” =>“马里奥”,“姓氏” =>“罗西”,“描述” =>“仅在此处进行描述。”)

My class: 我的课:

class Person {
    private $name;
    private $surname;
    private $description;

    public function __contruct(/*arguments or array here*/) {
    }
}

A clean and easy solution is to use the json_decode and json_encode functions. 一个干净而简单的解决方案是使用json_decodejson_encode函数。

http://php.net/json_decode http://php.net/json_decode

$object = json_decode(json_encode($_POST['formdata']), FALSE);

json_decode converts your formdata to an serialized object and the second parameter of json_encode (false) prevents the data from being converted back to an array . json_decode将您的json_decode转换为序列化的对象,而json_encode的第二个参数(false)可防止将数据转换回array

Don't directly use $_POST in the function rather send it as parameter to the function 不要在函数中直接使用$_POST而是将其作为参数发送给函数

Function call from CLASS object: 从CLASS对象调用函数:

$args = array(
   'val1' => $_POST['val1'],
   'val2' => $_POST['val2'],
   'val3' => $_POST['val3']
);
$obj->funct($args);

Function definition in CLASS: CLASS中的函数定义:

public function funct ($param = array()) {
   print_r( $param );
}

If your form has data beyond one Person , then one Person is not enough to represent your form! 如果您的表单中的数据超过一个Person ,那么一个Person不足以代表您的表单!

Have a class PersonForm (or whatever name it may be), and pass in the $_POST array as an argument. 有一个PersonForm类(或它的任何名字),并传入$_POST数组作为参数。

The PersonForm can then create (either by new or by using a PersonFactory class) the Person objects using some of the data from the array. 然后, PersonForm可以使用数组中的某些数据(通过new或使用PersonFactory类)创建Person对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM