Reputation: 1557
class hydra {
var $dbcon;
function __construct($ezSQL){
$this -> dbcon=$ezSQL;
}
}
class user extends hydra{
function foo(){
echo "bar is: ".$this->dbcon;
}
}
I then call:
$hydra = new hydra($ezSQL);
However, at this point I get the following error:
Fatal error: Cannot instantiate abstract class hydra
How do set up a class that will inherit all of it's children's functions so I can do something like this:
$hydra = new hydra("foobar");
$hydra -> foo();
output:
bar is: foobar
Upvotes: 0
Views: 627
Reputation: 57650
You can not get children's functionality into parent. Just think, does Mom gets her look from her daughter? No. Its the child who inherits from parent.
The code you have given does not throw any error. But from the error It seems hydra is an abstract class. And as you want to call the childrens method as hydra you should have that method as abstract.
abstract class hydra {
var $dbcon;
function __construct($ezSQL){
$this -> dbcon=$ezSQL;
}
abstract public function foo();
}
Now you can instantiate user
but call the foo()
method as hydra
. Its help full in Type hinting.
function dofoo(hydra $h){
$h->foo();
}
$user = new user("bar");
dofoo($user);
Here the function dofoo
sees $h
as a hydra
instance.
Upvotes: 1
Reputation: 1006
I think you are getting the idea of inheritance wrong.
A parent does not inherit functions from a child, the CHILD inherits functions from the parent.
In your case, hydra
does not have a function foo()
.
The class user
inherits the constructor function and the properties of hydra
, therefore the code below is what would work.
$hydraChild = new user("foobar");
$hydraChild -> foo();
Once again, you CANNOT set up a class that inherits all of it's children's functions. That is not how object-oriented programming works.
Upvotes: 0