【问题标题】:Learning OOP in PHP. Is this the correct way to do this?在 PHP 中学习 OOP。这是正确的方法吗?
【发布时间】:2014-06-14 15:22:08
【问题描述】:

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

【问题讨论】:

  • 恕我直言,将数据成员公开并不是一个好主意。请改用 getter 和 setter。
  • 每次页面加载时都会执行echo $name-&gt;processName($_POST['name']);这一行,无论是否包含类。如果不包含 class.php,您应该会收到错误、警告或通知,具体取决于您的配置。
  • 我建议你结帐 laravel。
  • @MichaelCalkins 哇,升级很快!此问题也被标记为 OOP,因此将 OP 定向到 laravel 并不是真正有效的评论。

标签: php oop


【解决方案1】:

您的权利,您不需要在该函数中输入 $_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();

【讨论】:

  • s/protected/private
  • @PeeHaa - 保护它可能是有效的。取决于它的用途
  • 是的可能有效。但经验法则应该是private,除非需要protected
  • 您需要确保在 html 上方包含 class 的脚本
【解决方案2】:

来自 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多