对于专家:使用 PHP 的对象中的快速条件 (cond ? true : false) 的替代品是什么?
For experts: What's the replacement for fast conditional (cond ? true : false) in objects using PHP?
对于你们中的许多人来说,也许这是一个愚蠢的问题,但今天我遇到了一个疑问:
有没有办法使用快速条件? true : false 在对象调用上无需重新创建代码或使用 if/else 语句?让我解释一下...
如何调用这样的东西?:
$users = DB::table('users')
->where('votes', '>', 100)
(condition ? '->orWhere('name', 'John')' : '')
->get();
你收到了吗?在对象内部调用...
它被称为ternary operator。不,你不能做你想做的事。您将不得不使用常规的 if 语句。
$query = DB::table('users')
->where('votes', '>', 100);
if (condition) {
$query->orWhere('name', 'John');
}
$users = $query->get();
对于你们中的许多人来说,也许这是一个愚蠢的问题,但今天我遇到了一个疑问:
有没有办法使用快速条件? true : false 在对象调用上无需重新创建代码或使用 if/else 语句?让我解释一下...
如何调用这样的东西?:
$users = DB::table('users')
->where('votes', '>', 100)
(condition ? '->orWhere('name', 'John')' : '')
->get();
你收到了吗?在对象内部调用...
它被称为ternary operator。不,你不能做你想做的事。您将不得不使用常规的 if 语句。
$query = DB::table('users')
->where('votes', '>', 100);
if (condition) {
$query->orWhere('name', 'John');
}
$users = $query->get();