2011-08-24 72 views
0

我正在使用codeigniter表单验证。要显示表单错误,它使用这个如何将此语法转换为正常的php if else

$this->data['message'] = (validation_errors() ? 
    validation_errors() : 
    ($this->auth_lib->errors() ? 
     $this->auth_lib->errors() : 
     $this->session->flashdata('message'))) 

我不明白这个语法。我认为这是一个if else的陈述。这很难理解。

任何人都可以将其转换为正常的if else语句吗?

因为我现在要改变错误信息格式:

$this->message->set_error($msg=array('Test 1','Test 2')); 
$message=$this->message->get_message(); 
$this->data['message']=$message; 

任何人,请简化的语法。谢谢。

+1

这不是来自CI,而是PHP本身:[ternary operator](http://www.php.net/manual/en/language.operators。 comparison.php#language.operators.comparison.ternary) – NullUserException

+2

这就是为什么我讨厌三元经营者,除非它是非常短的东西。 – Matt

+1

一旦你开始使用三元条件运算符,你会学会去爱它! :d – zombat

回答

6

一个? B:C ==如果(a){B}其他{C}

if (validation_errors()) 
{ 
    $this->data['message'] = validation_errors(); 
} 
else if ($this->auth_lib->errors()) 
{ 
    $this->data['message'] = $this->auth_lib->errors(); 
} 
else 
{ 
    $this->data['message'] = $this->session->flashdata('message'); 
} 
4

$this->data['message'] = (validation_errors() ? validation_errors() : ($this->auth_lib->errors() ? $this->auth_lib->errors() : $this->session->flashdata('message')))

是多三元操作等效于:

if (validation_errors()) 
    $this->data['message'] = validation_errors(); 
elseif ($this->auth_lib->errors()) 
    $this->data['message'] = $this->auth_lib->errors(); 
else 
    $this->data['message'] = $this->session->flashdata('message'); 
2

您发布使用ternary operators的代码。它们可以非常方便,但如果嵌套其中几个,它们也会时不时混淆。这里是没有三元运算符的等价书写...

if(validation_errors()) 
    { 
     $this->data['message'] = validation_errors(); 
    } 
    else 
    { 
     if($this->auth_lib->errors()) 
     { 
      $this->data['message'] = $this->auth_lib->errors(); 
     } 
     else 
     { 
      $this->data['message'] = $this->session->flashdata('message'); 
     } 
    }