Jump to content

[SOLVED] object inheiritance help


devdavad

Recommended Posts

in my learning PHP book it gave me an exercise on object oriented programming. The exercise was to create a class called base_calc and have 4 other classes inheirit from it (mult_calc, div_calc, add_calc, sub_calc) but overrides one of the functions in base_calc. Here's what I've gotten so far.

<?php
class base_calc {
        var $number1;
        var $number2;
        function base_calc($n1, $n2) {
                $this->number1 = $n1;
                $this->number2 = $n2;
        }
        function calculate() {
                echo $number1 . $number2;
        }
}
class add_calc extends base_calc{
        function calculate() {
                echo $number1 + $number2;
        }
}
class sub_calc extends base_calc{
        function calculate() {
                echo $number1 - $number2;
        }
}
class mult_calc extends base_calc{
        function calculate() {
                echo $number1 * $number2;
        }
}
class div_calc extends base_calc{
        function calculate() {
                echo $number1 / $number2;
        }
}
$object = new base_calc("3.0","5.0");
$object->calculate();
?>

However this does not print out anything. Does anyone know what I might be doing wrong?

Link to comment
https://forums.phpfreaks.com/topic/110631-solved-object-inheiritance-help/
Share on other sites

        function calculate() {
                echo $number1 . $number2;
        }

$number1 and $number2 are local variables to that function when written that way. to access the object's parameters, you need to use $this->number1 just like you did in the first method:

        function calculate() {
                echo $this->number1 . $this->number2;
        }

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.