Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

inheritance - Call parent constructor before child constructor in PHP

I was wondering if its possible to call the parents __construct(), before the child's __construct() with inheritance in PHP.

Example:

class Tag {
     __construct() {
         // Called first.
     }
}

class Form extends Tag {
     __construct() {
         // Called second.
     }
} 

new Form();

Ideally, I would be able to do something in between them. If this is not possible, is there an alternative, which would allow me to do this?

The reason I want to do this is to be able to load a bunch of default settings specific to the Tag that Form can use when __construct() is called.

EDIT: Sorry forgot to add this.. I'd rather not call the parent class from the child class. It's simply because it exposes some private data (for the parent) to the child, when you pass it as an argument

This is what I want to do:

$tag = new Tag($privateInfo, $publicInfo);
$tag->extend(new Form()); // Ideal function, prob doesn't work with inheritance.

Tag.php

class Tag {
     private $privateInfo;
     public $publicInfo;
     __construct($private, $public) {
         $this->privateInfo = $private;
         $this->publicInfo = $public;
     }
} 

Form.php

class Form extends Tag {

     __construct() {
         echo $this->publicInfo;
     }
} 

Make sense?

Thanks! Matt Mueller

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just call parent::__construct in the child.

class Form extends Tag
{
    function __construct()
    {
        parent::__construct();
        // Called second.
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...