如何在数学类中创建减法方法?
我正在学习 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 am studying OOP and this is my first study project.
I created a Math class and also created an add method. But when I am trying to create a subtract method I don't know where I am getting a problem.
Please kindly help and give me information where I can get more detailed information on 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;
}
}
I am calling this class in my index.php like this:
<?php
include("Math.php");
$c = new Math();
$result = $c->subtract(100,10,20,45);
echo $result;
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
握住我的手2024-11-11 22:19:43
我建议您观看此视频
整洁代码讲座 - 继承、多态性和& ;测试。
这可能会帮助您更好地理解 OOP,并且演讲中的一个示例与您尝试制作的示例非常相似。
灼疼热情2024-11-11 22:19:43
功能行 is_int($sub - func_get_arg($i));
不正确。我认为您打算将其用作三元运算符并添加额外的逻辑。这是我的重写:
public function subtract() {
$args = func_get_args();
$sub = array_shift($args);
foreach ($args as $arg) {
is_int($sub - $arg) and $sub -= $arg
or die('use only integers please');
}
return $sub;
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这里有一些小问题:
一个可行的解决方案如下所示:
There are a few small problems here:
A working solution would look like this: