PHP class extensions

I have two classes that work separately from the other, but they extend the same class. Is it possible for them to work in a single instance of an extended class. I want the constructor of the extended class to run only once.

I know this is wrong, but something like this:

<?php
$oApp = new app;
class a extends $oApp {}
class b extends $oApp {}

      

+2


a source to share


2 answers


And, in this case, I believe you want to pass the class as a parameter to the other two classes:



/**
 * 
 */
class abParent{
    /**
     * @var app
     */
    protected $app;
    /**
     *
     * @param app $app
     */
    public function __construct(app &$app){
        $this->app = &$app;
    }
}

class a extends abParent{}
class b extends abParent{}


$app = new app();
$a = new a($app);
$b = new b($app);

var_dump($a, $b);

      

+2


a source


What you want is this:

<?php
$oApp = new app;
class a extends app{}
class b extends app{}

      



If you have any __constructor

in your child classes, make sure they are called parent::__constructor

, otherwise they probably won't work as expected.

0


a source







All Articles