php - 如何在数学类中创建减法方法?

标签 php oop class methods subtraction

我正在学习 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;
?>

最佳答案

这里有一些小问题:

  1. 您的循环永远不会终止,因为 $i 的递增超出了 while 循环的范围。
  2. 第一次设置 $sub 应该发生在 while 循环之前。我假设你的减法函数是为了从第一个参数中减去后面的参数。现在,$sub 在每次循环中都会重置。
  3. $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/

相关文章:

php - 类扩展或接口(interface)如何工作?

php - Phalcon:多态关联

希伯来字母的 PHP 范围

c# - 接口(interface)和类之间有什么区别,当我可以直接在类中实现方法时为什么要使用接口(interface)?

c# - 如何调用 setter 内部的逻辑?

c# - 为什么 C# 不允许使用组合的类型对接口(interface)进行隐式转换?

php - "User follows"与 PropelORM - 三向关系

php - 简单选择查询中返回的行 ID 不正确

c++ - 命令设计模式的实现有一些错误?

java - 不同类的 Log4J 记录器