-1

我有两个将根据条件运行的功能。代码就像

$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() 为假,它不会检查 function1()。

4

4 回答 4

1

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

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

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

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

如果早期版本

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

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

于 2012-12-24T07:25:11.167 回答
1

您不能返回值并使用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

于 2012-12-24T07:25:33.227 回答
0

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

于 2012-12-24T07:22:52.117 回答
0

它应该是

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

或者

$contact = $this->A() ?: $this->B();
于 2012-12-24T07:52:01.410 回答