计算输出是不希望的

时间:2011-03-16 12:54:00

标签: php class

我正在尝试在此处获取类定义和使用计算

的基础知识

这是代码

<?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);

?>

我的浏览器中显示的是:

  

您的数字总和:0

为什么不是9?

3 个答案:

答案 0 :(得分:4)

你应该做

class calculator {
    //...
}
$number1 = 4;
$number2 = 5;
$cal = new calculator;
$cal->add($number1,$number2);

class calculator {
    var $number1 =4;
    var $number2 =5;
    //...
}
$cal = new calculator;
$cal->add($cal->number1,$cal->number2);

答案 1 :(得分:2)

您传递的$number1$number2的值是多少? $number1$number2$cal->number1$cal->number2不同。

您正在定义一个对象的两个属性,并将两个不同的独立变量传递给该类的函数。你基本上有两对数字 - 对象中有一对,值为4和5,一个在函数之外,没有值(均为0),然后你要添加它们。

你可以试试这个:

<?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');

或者这个:

<?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();

或者这个:

<?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 :(得分:2)

您的$number1$number2被宣布在班级范围内。

但是,当您致电$cal->add($number1, $number2)时,您现在已超出该范围,因此这些值未定义。