【发布时间】:2011-02-17 18:18:47
【问题描述】:
好的,我测试了下面的内容,我会告诉你我发现了什么:
echo ('-1' < 0) ? 'true' : 'false'; // will echo "true"
echo ('1' > 0) ? 'true' : 'false'; // will echo "true"
# Notice that '-1' and '1' are strings
现在让我们从数据库中获取一个数组,在过滤所有结果后,只获取带有UID = 1 的行。
$this->a = array(
[0] => array(
'UID' => '1',
'PID' => '91',
'Amount' => '-1'
),
[1] => array(
'UID' => '1',
'PID' => '92',
'Amount' => '1'
),
[2] => array(
'UID' => '1',
'PID' => '93',
'Amount' => '1'
)
);
现在我想创建一个函数posAmount($PID),如果'Amount' > 0,则返回true,如果'Amount' < 0,则返回false。 (注意:Amount = 0 是我不在乎的东西)。我也想写成类似的函数negAmount($PID),它返回与第一个完全相反的函数。现在,我想向您介绍我的双功能:
public function posAmount($pid)
{
foreach ($this->a as $a)
{
if (count($this->a) == 0) { return false; }
return ($a['PID'] == $pid and $a['Amount'] > 0) ? true : false;
}
}
public function negAmount($pid)
{
foreach ($this->a as $a)
{
if (count($this->a) == 0) { return false; }
return ($a['PID'] == $pid and $a['Amount'] < 0) ? true : false;
}
}
很酷的事实是,关于第一个数组(我检查了 var_dump() 在整个脚本中保持其性质):
$istance->negAmount(91); // Returns true, as expected
$istance->posAmount(92); // Returns false, as NOT expected.
# Why do God wants me to get mad?
【问题讨论】:
-
必须是这一行:
if (count($this->votes) == 0) { return false; } -
return ($a['PID'] == $pid and $a['Amount'] < 0) ? true : false可以写成return ($a['PID'] == $pid and $a['Amount'] < 0),为什么在每个循环迭代中都调用if (count($this->votes) == 0) { return false; }?这是一种不好的做法。 -
@BoltClock,不,这是一个错字。很抱歉。
-
您刚刚发现了为什么弱和动态(它们是分开的,我知道,但两者都在这里发挥作用)打字会很糟糕的一个原因;)
-
感谢您纠正错字。我更新了我的答案以包含工作代码和解释。