Are constructors inherited or do they belong to the class they are defined in? I only have seen examples with constructors of subclasses which call superclass' constructors. This is my current code, which can give some hint about what's going on. (I will change the code according to your replies. If I can use the constructor of the superclass, I won't define a constructor for each subclass and call superclass' constructor from each.
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->viewer = $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
$this->viewerid = $viewerid;
}
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
If the subclass has no constructor at all, the compiler will automatically create a public constructor that simply calls through to the default constructor of the superclass.
Subclass Constructors Invocation of a superclass constructor must be the first line in the subclass constructor.
Constructors are never overriden or inherited. In fact, they cannot be called virtually. However, you can create a constructor in the subclass which calls a constructor in the parent class.
According to my understanding, PHP doesn't auto-call parent's constructor if child constructor is defined. Otherwise it does.
In child constructor you have to call parent's constructor manually.
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->viewer = $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
parent::__construct($viewerid); // manual call
// do your stuff here...
$this->viewerid = $viewerid;
}
parent::__construct(params);
use for calling superclass constructor
PHP4
PHP doesn't call constructors of the base class automatically from a constructor of a derived class. It is your responsibility to propagate the call to constructors upstream where appropriate.
PHP5
PHP doesn't call constructors of the base class if new constructor defined. If you define a constructor for derived class It is your responsibility to propagate the call to constructors upstream where appropriate. parent::__construct(params)
Constructors
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->vieverid= $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
parent::__construct($viewerid);
// Extra code if you want
}
}
class viewactor_construct extends view{
// Works in PHP5
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With