用if语句替换一行代码


Replacing a line of code with an if statement

我遵循了这里经常推荐的教程构建PHP MVC应用程序,我遇到了一行代码,这是使用?:缩短的if语句。因为我不是很熟悉这种简短的代码,所以我试着按照我的方式重新创建它。

$this->params = $url ? array_values($url) : [];

我想出了:

    if(isset($url))
    {
      $this->params = array_values($url);
    }

这是做完全相同的事情吗?还是我错过了什么?它可以工作,看起来它在做同样的事情,但我想确定。

由于一些答案取决于$url的状态,下面是完整的代码:

<?php
  class App
  {
    protected $controller = 'home';
    protected $method = 'index';
    protected $params = [];
    public function __construct()
    {
      $url = $this->parseUrl();
      if(file_exists('../app/controllers/' . $url[0] . '.php'))
      {
        $this->controller = $url[0];
        unset($url[0]);
      }
      require_once '../app/controllers/' . $this->controller . '.php';
      $this->controller = new $this->controller;
      if(isset($url[1]))
      {
        if(method_exists($this->controller, $url[1]))
        {
          $this->method = $url[1];
          unset($url[1]);
        }
      }
      $this->params = $url ? array_values($url) : [];
      call_user_func_array([$this->controller, $this->method], $this->params);
    }
    public function parseUrl()
    {
      if(isset($_GET['url']))
      {
        return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
      }
    }
  }

if (isset($url))将检查是否存在一个集合变量。

if ($url)将检查变量本身是否为真值。

你应该使用if ($url)

顺便说一下,您不熟悉的代码称为三元语句!它在其他一些语言(例如Ruby)中很常见,了解它是如何工作的是很有用的。

如果你不知道我说的真值是什么意思,你应该阅读更多关于布尔类型转换的知识。

最简洁的方法是:

$this->params = [];
if($url) {
    $this->params = array_values($url);
}

if($url) {
    $this->params = array_values($url);
}
else {
    $this->params = [];
}

称为三元语句。[value] = [condition] ? [if true] : [else] .

http://php.net/manual/en/language.operators.comparison.php

相当于:

 if(isset($url))
 {
     $this->params = array_values($url);
 } else {
     $this->params = [];
 }

Phpisset用于检查variavble是否为defined。仅return true和false基于variable是否定义

关于isset的更多信息请阅读http://php.net/manual/en/function.isset.php

另一方面,ternary opreatorsif-else的缩写形式,更方便书写

Ternary operators是有用的,当你有multiple conditions,而不是使用多个if-else,你可以使用ternary,就像这个例子

$data= ($value== 1) ? "one" : (($value== 2)  ? "two" : "other");