Posted: Wed Mar 07, 2007 1:09 pm
Yes, you can override methods. This allows for polymorphism. This means that you can write your code to work with any shopping cart, it doesn't care what specific kind of shopping cart, just that you can put items into it, take items out of it, and get a total. All that matters is that all your shopping carts have the same functionality (implement the same interface).kendall wrote:So you can overwrite a function from the original class in the extended one?The proper way to do it would be to override calculate_final_total in the discounted cart. That way if the customer changes his mind all you have to do is change your code so that the discounted cart us used and not have to worry about passing true or false to calculate_final_total.
would you believe me if i said i was just asking that same question?
thanks...
im not to good with OOP
Take the following as an example
Code: Select all
class Animal
{
function makeSound()
{
die('you forgot to override me') ;
}
function sleep()
{
echo 'zzzzz' ;
}
}
class Cat extends Animal
{
function makeSound()
{
echo 'meow' ;
}
}
class Chicken extends Animal
{
function makeSound()
{
echo 'bawk bawk bigawk!' ;
}
}
$animals = array() ;
$animals[] = new Chicken() ;
$animals[] = new Cat() ;
$animals[] = new Chicken () ;
foreach( $animals as $animal )
{
$animal->makeSound() ;
}
// outputs
// bawk bawk bigawk
// meow
// bawk bawk bigawkWithin foreach, you don't care what kind of animal it is, all that you care is that all animals have the same functionality. So you could quite easily add a donkey animal, stick it in your array, and the rest of the code will still work.
This is kinda how your shopping cart would work from the approach you took (there are other ways as well).
In PHP 5 you can enforce this a bit better by using interfaces and abstract classes
Code: Select all
interface IAnimal
{
public function makeSound() ;
public function sleep() ;
}
abstract class Animal implements IAnimal
{
public function sleep()
{
echo 'zzzzz' ;
}
}
class Cat extends Animal
{
public function makeSound()
{
echo 'meow' ;
}
}
class Chicken extends Animal
{
public function makeSound()
{
echo 'bawk bawk bigawk!' ;
}
}