If I do not define a constructor for a subclass, can I use the superclass constructor directly?

Are constructors inherited or belong to the class in which they are defined? I just saw examples with subclass constructors that call superclass constructors. This is my current code, which may give some hint of what is happening. (I will modify the code according to your answers. If I can use the superclass constructor, I will not define a constructor for each subclass and call the 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;
 }
+5
source share
3 answers

parent::__construct(params); use to call the constructor of superclasses

PHP4

PHP . , .

PHP5

PHP , . , . :: __ (PARAMS)

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
}
+3

, PHP , child. .

.

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;
 }
+3

, . , parent:: __ construct() .

.

+1
source

All Articles