Null object pattern: Difference between revisions

Content deleted Content added
m ce lead
Line 385:
{
public function makeSound()
{
echo "Woof...\n";
}
}
Line 393:
{
public function makeSound()
{
echo "Meowww...\n";
}
}
Line 401:
{
public function makeSound()
{
// silence...
}
Line 407:
 
$animalType = 'elephant';
 
switch($animalType) {
function makeAnimalFromAnimalType(string $animalType): Animal
case 'dog':
{
$animal = new Dog();
switch($animalType) {
break;
case 'catdog':
$animal = return new CatDog();
break;case 'cat':
return new Cat();
default:
$animal = new NullAnimal();default:
break return new NullAnimal();
}
}
 
makeAnimalFromAnimalType($animalanimalType)->makeSound(); // ..the null animal makes no sound
 
function animalMakeSound(Animal $animal): void
{
$animal = new Dog->makeSound();
}
 
foreach ([
makeAnimalFromAnimalType('dog'),
makeAnimalFromAnimalType('NullAnimal'),
makeAnimalFromAnimalType('cat'),
] as $animal) {
// That's also reduce null handling code
animalMakeSound($animal);
}
$animal->makeSound(); // ..the null animal makes no sound
</syntaxhighlight>