函数返回对象

时间:2018-11-15 08:36:14

标签: php oop

我正在跟踪遇到问题的教程

function old($field) {
    return request($field);
}

function request($field = null) {
    $request = new \App\Helper\Request();
    if(is_null($field))
        return $request;
        return $request->input($field);
}

我不知道为什么我们应该将$ filed设置为null,以及在使用两次return时会发生什么?在寄存器菜单文本框中进行验证后,使用旧函数会保留真实值

以下源代码是管理请求的请求类:

class Request
{
public function input($filed, $post = true)
{
if ($this->isPost() && $post)
        return isset($_POST[$filed]) ? htmlspecialchars($_POST[$filed]) : "";

    return isset($_GET[$filed]) ? htmlspecialchars($_GET[$filed]) : "";
}


public function all($post = true)
{
    if ($this->isPost() && $post)
        return isset($_POST) ? array_map('htmlspecialchars' , $_POST) : null;

    return isset($_GET) ?array_map('htmlspecialchars' , $_GET) : null;
}


public function isPost()
{
    return $_SERVER['REQUEST_METHOD'] == 'POST';
}
}

PS:如果有人需要更多信息,请告诉我,我将发送完整的源代码。 谢谢

2 个答案:

答案 0 :(得分:0)

  

我不知道为什么我们应该将$ field设置为null以及使用两次return会发生什么?

您没有将$field设置为null,但是$field是一个可选参数,这意味着,如果没有参数传递给函数,则null将用作默认值。

然后这个:

$request = new \App\Helper\Request();

if(is_null($field))
    return $request;
return $request->input($field);

简而言之,如果$fieldnull,则返回new \App\Helper\Request()的结果,否则返回$request->input($field)的结果,其中$request=new \App\Helper\Request()

即使我可能在if语句中只有一条单行指令,我还是更喜欢使用括号来提高可读性和最佳理解。

答案 1 :(得分:-1)

缩进的重要性

function old($field) {
   return request($field);
}

function request($field = null) {
   $request = new \App\Helper\Request();
   if(is_null($field)) {
      return $request;
   }
   return $request->input($field);
}