我正在 PHP 5 中做一个元素,我想将名称、电子邮件、密码等表单元素的值设置为 php 中对象的属性。我该怎么做呢?请帮忙。
最佳答案
您将不得不创建 php 对象来存储此类属性,或者如果您不想走那条路,您将不得不创建一个程序函数来存储这些值并将其放置在它应该去的地方。
对象示例
<?php
class User {
private $name;
private $email;
private $password;
public function __construct(array $data) {
$this->name = isset($data['name'] ? trim($name) : null;
$this->email = isset($data['name'] ? trim($email) : null;
$this->password = isset($data['password']) ? trim($password) : null;
}
// Setters and getters defined here as well
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = trim($name);
}
}
所以在你的 html 表单中,
<form method="post" action="add_user.php">
<input type="text" name="user[name]" id="name" />
<input type="email" name="user[email]" id="email" />
<input type="password" name="user[password]" id="password" />
<input type="submit" value="Add User" />
</form>
要注意的主要事情是表单的方法和 Action 属性,方法是你如何通过 http 播种它, Action 是你发送这些值的位置,所以在我的演示中它被发送到一个名为在同一目录中添加_user.php,并通过 POST 方法。
信息将由 php 接收,如下所示:
$_POST['user'] => array('name' => '', 'email' => '', 'password' => '');
所以你所做的只是在你的 add_user.php 脚本中:
<?php
$userData = isset($_POST['user']) ? $_POST['user'] : array();
$User = new User($userData);
// FRom here on out you can do whatever you want with this.
关于php - html 表单元素值到 php 对象属性属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20859283/