dongming6201 2011-03-16 12:53
浏览 6
已采纳

计算输出是不希望的

I'm trying to get the basics down here of class definition and using a calculation

Here's the code

<?php

class calculator {
    var $number1 = 4;
    var $number2 = 5;

    function add ($a,$b){
        $c = $a + $b;
        print ("the sum of your numbers: $c");
        print ($c);
    }

}

$cal = new calculator;
$cal->add($number1,$number2);

?>

What appears in my browser is:

The sum of your numbers: 0

Why not the 9?

  • 写回答

3条回答 默认 最新

  • doukong9982 2011-03-16 12:55
    关注

    What are the values of $number1 and $number2 that you are passing in? $number1 and $number2 are not the same as $cal->number1 and $cal->number2.

    You're defining two properties of an object, and passing two distinct, separate variables into the class's function. You basically have two pairs of numbers - one pair in the object, with values of 4 and 5, and one outside the function with no values (both 0) which you are then adding.

    You could try this:

    <?php
    class calculator {
        private $number1 = 4;
        private $number2 = 5;
    
        function add ($a, $b){
            $c = $this->$a + $this->$b;
            print ("the sum of your numbers: $c");
            print ($c);
        }
    
    }
    
    $cal = new calculator;
    $cal->add('number1', 'number2');
    

    Or this:

    <?php
    class calculator {
        private $number1 = 4;
        private $number2 = 5;
    
        function add (){
            $c = $this->number1 + $this->number2;
            print ("the sum of your numbers: $c");
            print ($c);
        }
    
    }
    
    $cal = new calculator;
    $cal->add();
    

    Or this:

    <?php
    class calculator {
        function add ($a, $b){
            $c = $a + $b;
            print ("the sum of your numbers: $c");
            print ($c);
        }
    
    }
    
    $cal = new calculator;
    $cal->add(4, 5);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集