开发者

output of calculation is undesired

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?


You should either do

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

or

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


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


Your $number1 and $number2 are being declared inside the scope of the class.

However when you call $cal->add($number1, $number2) you are now outside of that scope, so those values are undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜