使用PHP三元运算符返回特定值


Using the PHP ternary operator to return a specific value

我已经在谷歌上搜索过了,并浏览过堆栈溢出。我正在尝试缩短我的代码,下面我有一个工作方法,我想用三进制风格重写。有人能告诉我这是否可能吗?如果可能的话,我做错了什么。谢谢

public function __get($field){ //refactor this using ternary method
    if($field == 'user_id'){
        return $this->uid;
    } else {
        return $this->fields[$field];
    }
}

我从这个开始:

($field == 'user_id') return $this->uid : return $this->fields[$field];

它给了我一个意外的返回错误。

我尝试使用另一个堆栈溢出解决方案,它在值之前列出了返回,但没有成功。

return $field == 'user_id' ? $this->uid : $this->fields[$field];

这给了我一些关于意外公共的其他错误,比如我的方法没有正确关闭。

我猜它是这样的;您将代码重构为:

public function __get($field){ //refactor this using ternary method
        return $field == 'user_id' ? $this->uid : $this->fields[$field];
    }
}
public function otherfunction() { /* ... */ }

大括号不匹配,因此它关闭了类定义,下一个语法分析器错误是'unexpected public':)