我正在学习 OOP,这是我的第一个学习项目。
我创建了一个 Math 类,还创建了一个 add 方法。但是当我尝试创建减法方法时,我不知道在哪里遇到问题。
请帮助我并向我提供有关 OOP 的更多详细信息。
<?php
class Math
{
/**
*
* @return int
*/
function add()
{
$args = func_num_args();
$sum = 0;
$i = 0;
for ( $i; $i < $args; $i++ )
{
is_int(func_get_arg($i)) ? $sum += func_get_arg($i) : die('use only integers, please');
}
return $sum;
}
function subtract()
{
$args = func_num_args();
$sub = 0;
$i = 0;
while($i < $args)
{
$sub = func_get_arg($i);
if (is_int(func_get_arg($i)))
{
is_int($sub - func_get_arg($i));
}
}
$i++;
return $sub;
}
}
我在我的index.php中这样调用这个类:
<?php
include("Math.php");
$c = new Math();
$result = $c->subtract(100,10,20,45);
echo $result;
?>
最佳答案
这里有一些小问题:
- 您的循环永远不会终止,因为 $i 的递增超出了 while 循环的范围。
- 第一次设置 $sub 应该发生在 while 循环之前。我假设你的减法函数是为了从第一个参数中减去后面的参数。现在,$sub 在每次循环中都会重置。
- $sub 的值永远不会被循环中的减法运算更新。您需要根据减法为 $sub 分配一个新值。您可以为此使用 -= 简写,就像在 add() 方法中使用 += 简写一样。
一个可行的解决方案如下所示:
$sub = func_get_arg( $i ); // At this point $i == 0
while ( $i < $args ) { // Loop while $i is less than the number of args
$i++; // Increment $i
$operand = func_get_arg( $i ); // Name the argument for clarity
if ( is_int( $operand )) { // Make sure the $operand is an integer
$sub -= $operand; // Update $sub by subtracting $operand from it
} else {
// Do some error handling here...
}
}
关于php - 如何在数学类中创建减法方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5842292/