我正在测试 Heredoc 和 ||功能
function test()
{
$obj = [(object)['col1'=>'val1'],
(object)['col2'=>'val2'],
(object)['col3'=>'val3']];
$output = '';
$mystring = <<<EOT
a non empty string
EOT;
foreach($obj as $prop)
{
foreach($prop as $i)
{
$output .= <<<EOT
<div style='background-color:lightblue'>
\$head : {gettype($i)}
</div>
EOT;
}
}
$out = $output || $mystring || 'couldn\'t find something valuable';
echo $out;
}
test();
我得到了
的输出1
表示 bool 值 true。 我通过将逻辑放在括号中使其在某一时刻输出 $mystring 的内容,例如
echo ($output || $mystring);
它曾经输出:
a non empty string
它立即停止工作,我不确定是什么改变破坏了它。
在 JavaScript 中:
function test()
{
var obj = [{'col1':'val1'},
{'col2':'val2'},
{'col3':'val3'}];
var output = '';
var mystring ="a non empty string";
for(var prop in obj)
{
for(var i in prop)
{
output +=
"<div style='background-color:lightblue'>" +
i + " : " + typeof prop[i] +
"</div>";
}
}
out = output || mystring || 'couldn\'t find something valuable';
document.write(out);
console.log("outputting \n\t" + out);
}
test();
它在逻辑上与 php 略有不同,但 ||在分配期间按预期工作。我明白了
0 : string
0 : string
0 : string
对于上面的代码。如果像这样注释掉内部 for 循环
for(var prop in obj)
{
/*for(var i in prop)
{
output +=
"<div style='background-color:lightblue'>" +
i + " : " + typeof prop[i] +
"</div>";
}*/
}
我得到“mystring”的内容是
a non empty string
然后如果我像这样将 mystring 更改为空字符串
mystring = ""; //"a non empty string";
我明白了
couldn't find something valuable
php的“||”是如何实现的在分配工作期间? 谁能解释一下?
最佳答案
如果你在 php 中分配一个条件表达式,你总是得到一个 bool 值(即严格的 true
或 false
),它不像在 javascript 中那样工作,其中 "truthy"值被赋值,所以在 PHP 中
$a = "";
$b = 42;
$c = ($a || $b); // == true
在 javascript 中
var a = "";
var b = 42;
var c = (a || b); // == 42
遗憾的是,这是语言设计造成的。
正如@billyonecas 报道的那样,它也在对文档的评论中:http://php.net/manual/en/language.operators.logical.php#77411
要在 PHP 中获得类似的行为,我们必须做类似的事情:
$a = "";
$b = 42;
$c = ($a ?: $b); // newer php version
$c = ($a ? $a : $b); // older php version
如果您需要连接表达式,请使用括号:
$c = ($a ? $a : ($b ? $b : "not found"));
关于javascript - php "||"赋值逻辑与Javascript对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30234920/