Reputation: 16495
I have be below test script, and I am not sure as to why is is giving me errors. But at the same time working as expected (outputting a text 'woof');
abstract class Animal {
abstract function bark();
function MakeDog(){
return $this->bark();
}
}
class Dog extends Animal {
function bark(){
echo 'Woof';
}
}
$dog = new Dog();
echo $dog->MakeDog()->bark(); // this outputs 'woof' but with error.
Fatal error: Call to a member function bark() on a non-object in [...] 26
Line 26 is //echo $dog->MakeDog()->bark();
I am not sure to what the error is related to.
Upvotes: 0
Views: 175
Reputation: 791
You can't call bark()
after the method MakeDog()
and you can't use echo for return a message, for this use "return", the correct code:
<?php
abstract class Animal {
abstract function bark();
public function MakeDog(){
return $this->bark();
}
}
class Dog extends Animal {
function bark(){
return 'Woof';
}
}
$dog = new Dog();
echo $dog->MakeDog();
?>
Upvotes: 1
Reputation: 1065
Shouldn't it just be:
$dog = new Dog();
echo $dog->MakeDog();
Your function MakeDog already executes the method bark().
Upvotes: 1
Reputation:
Perhaps you don't need to echo even. This should work
$dog = new Dog();
$dog->MakeDog()->bark();
Also, get rid of return
just invoke bark()
in the MakeDog
function
function MakeDog() {
$this->bark();
}
Upvotes: 1