devdavad Posted June 17, 2008 Share Posted June 17, 2008 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 More sharing options...
rhodesa Posted June 17, 2008 Share Posted June 17, 2008 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; } Link to comment https://forums.phpfreaks.com/topic/110631-solved-object-inheiritance-help/#findComment-567567 Share on other sites More sharing options...
devdavad Posted June 17, 2008 Author Share Posted June 17, 2008 awesome thank you for that, I guess in this case I should probably make those variables global. Link to comment https://forums.phpfreaks.com/topic/110631-solved-object-inheiritance-help/#findComment-567569 Share on other sites More sharing options...
rhodesa Posted June 17, 2008 Share Posted June 17, 2008 no...the point of OOP is that the variables are specific to that instance of the object. if you make them global, all the instances would share the values. Link to comment https://forums.phpfreaks.com/topic/110631-solved-object-inheiritance-help/#findComment-567572 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.