我正在測試Heredoc和||功能php「||」賦值邏輯相比於Javascript
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();
我得到的
輸出代表一個布爾真。 我有它輸出的$通過將邏輯括號在一個點myString的內容,例如
echo ($output || $mystring);
,並用於輸出:
一個非空字符串
它停止工作後,我不知道什麼樣的變化打破了它。
在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:字符串
0:字符串
0:字符串
上面的代碼。如果註釋掉內的循環,像這樣
for(var prop in obj)
{
/*for(var i in prop)
{
output +=
"<div style='background-color:lightblue'>" +
i + " : " + typeof prop[i] +
"</div>";
}*/
}
我得到「MyString的」,這是
一個非空字符串的內容
,如果我再改的MyString到像這樣的空字符串
mystring = ""; //"a non empty string";
我得到
找不到有價值的東西
如何PHP的 「||」在分配工作中? 有人可以解釋它嗎?
請修復您的代碼格式。函數test(){'和'} test()'是未格式化的。 – Gogol
@ noc2spamツ謝謝。在我閱讀您的評論之前修復它.XD – Sarfaraaz