【问题标题】:return values on or condtion in php在php中返回值或条件
【发布时间】:2012-12-24 07:19:40
【问题描述】:

我有两个基于条件运行的函数。 代码是这样的

$contact=($this->function() or $this->function1())

public function()
{
 some codes
return contact;
}

 public function1()
  {
 some codes
 return contact;
   }

它在 $contact 中返回 bool true 或 false。我想返回值。怎么办?

如果我这样给予

$contact=$this->function() or $this->function1()

如果 function() 为 false,它不会检查 function1()。

【问题讨论】:

  • 那么应该返回哪个值呢?你想在$contact 中得到什么?
  • 或者像||这样使用?和return $contact; ?
  • -1。提供具体代码,而不是无法编译的代码。

标签: php return


【解决方案1】:

由于您使用布尔运算符或,

的结果
$this->function() or $this->function1()

是布尔值。 在 PHP 5.3 中,您可以像这样使用三元运算符

$contact=$this->function() ?: $this->function1();

如果是早期版本

if (!($contact=$this->function() )) $contact=$this->function1();

但是,一般来说,我认为您必须检查您的功能并更改其流程中的某些内容。可能必须在这两个中做出一个并在这个函数中做出决定。

【讨论】:

    【解决方案2】:

    您不能返回值并使用 OR 运算符
    一种方法是在函数中设置一个变量并为其赋值:

        $ret = "";
    function ()
    {
    
        $this->ret = "foo";
        return contact;
    }
    
    function1() {
        $this->ret = "Bar";
        return contact;
    }
    
    $a = function() or function1();
    unset($a);
    $newRet = $ret;
    

    更多详情请看这里:
    http://php.net/manual/en/language.operators.logical.php

    【讨论】:

      【解决方案3】:

      如果你想检查这两个函数,不管然后测试两者并将它们的结果保存在单独的变量中,然后在你的 if 比较中使用这两个变量

      【讨论】:

        【解决方案4】:

        应该是

        $contact = $this->A() or $contact = $this->B();
        

        或者

        $contact = $this->A() ?: $this->B();
        

        【讨论】:

          猜你喜欢
          • 2017-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-04
          • 2022-01-04
          • 1970-01-01
          • 2015-07-28
          相关资源
          最近更新 更多