为了回答这个问题,我们必须先说一下,你的函数语法可能存在错误(我会说“可能”,因为我还不能100%确定)。
public function edit($id == NULL)
应该是:
public function edit($id = NULL)
这段代码的意思是,如果本地变量ID没有被设置,它会将其设置为NULL,否则就设置它的值。这样做与代码的其余部分完全相符。
话虽如此,正如评论中所说,剩下的部分只是一个OR逻辑操作(好吧,你可以以任何方式看待它,我习惯将其解释为三元运算符,因为如果有人不知道它是如何工作的,这样做会稍微容易一些),我只是觉得应该指出,与许多其他语言不同,在PHP中,您可以直接在逻辑操作的第二个、第三个或任何参数中评估变量。
简而言之,您的操作:
$id == NULL || $this->data['user'] = $this->user_m->get($id);
也可以写成:
if ($id !== null) {
$this->data['user'] = $this->user_m->get($id);
}
当然,这是可读的,否则您也可以这样做:
$id !== NULL && $this->data['user'] = $this->user_m->get($id);
或者甚至:
$this->data['user'] = $id !== NULL ? $this->user_m->get($id) : $this->data['user'];
基本的三元运算符是:
condition ? iftrue : iffalse
你所说的“变化”实际上是一种逻辑操作的“使用”,称为
短路求值。事实上,OR逻辑运算符仅在左侧运算符为假值时才评估右侧运算符。因此:
$id == NULL || $this->data['user'] = $this->user_m->get($id);
$id == NULL
<-- 左操作数
$this->data['user'] = $this->user_m->get($id)
<-- 右操作数
根据上面所说,如果 $id == NULL 是假值(也就是说,如果 $id 不为 null),那么执行右操作数,将 $this->data['user'] 设为 $this->user_m->get($id),否则不执行任何操作。
$id!== NULL && $this->data ['user'] = $this->user_m->get($id);
或者更易读:$this->data['user'] = $id == NULL ? $this->user_m->get($id) : $this->data['user'];
简而言之,它基本上是说“如果id不为null(或者更精确地说,如果$id == null为falsey),则将$this->data ['user']设置为$this->user_m->get($id),否则只保持$id为null并继续进行”。 - briosheje