[英]Learning OOP in PHP. Is this the correct way to do this?
我刚开始学习做oop,我只是想把最基本的代码放在一起,以确保我正确理解事物。 我想捕获$ _POST变量中的表单条目并将其传递给对象,以便将其输出回浏览器。 没有SQL,没有安全措施,只是理解的证据。
这是表格:
<html>
<head>
<title>SignUp Form</title>
</head>
<body>
<?php
if(!empty($_POST['name'])) {
include_once "class.php";
} else {
?>
<form method="post" action="signup.php">
<label for="name">Enter name below:</label></br>
<input type="text" name="name" id="name"></br>
<input type="submit" value="Submit">
</form>
<?php
}
echo $name->processName($_POST['name']); ?>
</body>
</html>
这是班级:
<?php
class Process {
public $entry;
function __construct($entry) {
$this->entry = $entry;
}
public function processName($entry) {
return "You entered " . $this->entry . ".";
}
}
$name = new Process($_POST['name']); ?>
这现在没有错误,但似乎我不应该在表单页面和类页面上的对象中的echo语句中输入$ _POST。 这个对吗? 我应该在$ entry属性中收集它。 它工作正常,但我不认为执行是正确的。 提前致谢!
你不需要在该函数中输入$ _POST变量,你可以将其更改为此权限,并且无需输入帖子即可使用:
public function processName() {
return "You entered " . $this->entry . ".";
}
因为现在processName
函数对类的public $entry
变量没有任何作用,所以它只是回显你调用函数时放入的内容。
您可能想要做的是:
改变public $entry;
protected $entry;
然后:
public function getEntry() {
return $this->entry;
}
然后在你的html中,在构造类之后,你可以把它放到$entry
变量中:
echo $name->getEntry();
来自Symfony框架背景。 你可以这样做:
<?php
class Process
{
protected $post_var;
public function __construct($p)
{
$this->post_var = $p;
}
public function getData()
{
//checking if not post request
if(count($this->post_var) == 0) {
return false;
}
$result_arr = [];
//populating $result_arr with $_POST variables
foreach ($this->post_var as $key => $value) {
$result_arr[$key] = $value;
}
return $result_arr;
}
}
$process = new Process($_POST);
$data = $process->getdata();
if($data)
{
echo $data["name"];
}
?>
<form action="" method="post">
<input type="text" name="name"/>
<input type="submit" name="submit"/>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.