使用 return 时的 PHP 简写 If/Else

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18474559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:37:37  来源:igfitidea点击:

PHP Shorthand If/Else when using return

phpshorthand

提问by Ilia Rostovtsev

There are few nice ways to write shorthands in PHP.

在 PHP 中编写速记的好方法很少。

Less common but shortest example:

不太常见但最短的例子:

!isset( $search_order ) && $search_order = 'ASC';

More common but a little longer:

更常见但更长一点:

!isset( $search_order ) ? $search_order = 'ASC' : $search_order = NULL;

We can even combine examples above in to an amazing shorthand:

我们甚至可以将上面的例子组合成一个惊人的速记:

!isset( $_POST['unique_id'] ) && preg_match( '/^[a-zA-Z0-9]{8}$/', $_POST['unique_id'] ) ? $post_unique_id = $_POST['unique_id'] : $post_unique_id = NULL;


But how do we use examples above with functions and return, example:


但是我们如何将上面的示例与函数一起使用并返回,例如:

function filter_gender_request($data) {  
    preg_match('/(fe)?male/i', $data, $data);
    isset($data[0]) && return $data[0]; // It doesn't work here with return
}

At the same time, if I state the following, instead of isset($data[0]) && return $data[0];then everything works as expected:

同时,如果我陈述以下内容,isset($data[0]) && return $data[0];那么一切都按预期进行:

if (isset($data[0]) ) {
    return $data[0];
}

What am I doing wrong here? If the very first and shortest example works outside of function flawlessly, why then it doesn't work with return?

我在这里做错了什么?如果第一个和最短的例子在函数之外完美地工作,那么为什么它不能与 return 一起工作?

Is there a possibility to use shorthands with return?

有没有可能在 return 中使用速记?

回答by nickb

With your current syntax, what do you expect your function to return when $data[0]is not set? Surely you don't expect your function to notreturn anything, depending upon a condition.

使用您当前的语法,您希望函数在$data[0]未设置时返回什么?当然,您不希望您的函数返回任何内容,具体取决于条件。

The only alternative I see is the ternary operator, where you return something other than $data[0]when it is not set:

我看到的唯一选择是三元运算符,您可以在其中返回除$data[0]未设置之外的其他内容:

return isset($data[0]) ? $data[0] : null; 

回答by Viktor Sydorenko

For future googlers.

对于未来的谷歌员工。

Use php 7 null coalesce (??) operator

使用 php 7 null 合并 (??) 运算符

return $data[0] ?? null; 

回答by Marc B

Your amazing shortcut is actually rather hideous code. You are abusing the ternary operator, and that code is actually far LESS readable AND less maintainable than if you'd written it out. People expect ternaries to perform a test and return an either/or value. Performing assignment within it is NOT normal behavior.

你惊人的捷径实际上是相当可怕的代码。您正在滥用三元运算符,并且该代码实际上比您写出来的代码可读性和可维护性差得多。人们期望三元组执行测试并返回一个非此即彼的值。在其中执行分配不是正常行为。

回答by Leonard

The problem with your code is you are trying to execute a returnstatement as part of the ternary expression. The ternary operator generally results in an assignment as in:

您的代码的问题是您试图将return语句作为三元表达式的一部分执行。三元运算符通常会产生如下赋值:

$message = is_error() ? get_error() : 'No Errors';

This results in an assignment to $messagebased on the return value of is_error(). Your code is trying to process a program control statement within the operation. returncannot be assigned to the variable.

这将导致$message基于 的返回值分配给is_error()。您的代码正在尝试处理操作中的程序控制语句。return不能赋值给变量。

For this reason, what the other users have posted are better options for your situation.

出于这个原因,其他用户发布的内容是更适合您情况的选择。

回答by botenvouwer

oke I don't know what you are doing but this should work:

好吧,我不知道你在做什么,但这应该有效:

return ( isset($data[0]) ? $data[0] : false);

回答by James

Agreeing with what has been answered here, that shorthand is harder to read once you've gone away from it and come back, or worse, another developer in the future.

同意这里的回答,一旦你离开它并回来,或者更糟的是,未来的另一个开发人员,这个速记就更难阅读了。

Imagine yourself with even a small 500 line script file, with 40 lines of shorthand elseif as you use it, would you be ok trying to add or change code?

想象一下,即使是一个 500 行的小脚本文件,还有 40 行的速记 elseif,当您使用它时,您可以尝试添加或更改代码吗?

Especially when the subject or content is not something you're familiar with, it becomes a headache to debug or make additions.

尤其是当主题或内容不是您熟悉的东西时,调试或添加内容就变得很头疼。

This is much more manageable and doesn't matter what it's about, it's just code:

这更易于管理,并且无关紧要,它只是代码:

if ($var == 'unicorns')
  {
    $this->remove_horn;
  }
elseif ($var == 'horse')
 {
   $this->glue_on_horn;
 }
else
  {
    $this->must_be_a_zebra;
  }

just saying

只是说