在PHP中学习OOP。这是正确的方法吗?

时间:2014-06-14 15:22:09

标签: php oop

我刚开始学习做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属性中收集它。它工作正常,但我不认为执行是正确的。提前谢谢!

2 个答案:

答案 0 :(得分:0)

您不需要在该函数中输入$ _POST变量,您可以将其更改为此,并且无需输入帖子即可使用:

public function processName() {
    return "You entered " . $this->entry . ".";
}

因为现在processName函数没有对类的公共$entry变量做任何事情,所以它只是回显你调用函数时放入的内容。

您可能想要做的是:

public $entry;更改为protected $entry;

然后:

public function getEntry() {
    return $this->entry;
}

然后在你的html中,在构建类之后,你可以把它放到$entry变量中:

echo $name->getEntry();

答案 1 :(得分:0)

来自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>
相关问题