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.
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.
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.')
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.
$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
.
Don't directly use $_POST
in the function rather send it as parameter to the function
Function call from CLASS object:
$args = array(
'val1' => $_POST['val1'],
'val2' => $_POST['val2'],
'val3' => $_POST['val3']
);
$obj->funct($args);
Function definition in 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!
Have a class PersonForm
(or whatever name it may be), and pass in the $_POST
array as an argument.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.