PHP Classes Extend
-
01-10-2019 - |
Question
I have two classes that work seperate from another, but they extend the same class. Is it possible to have them work the same instance of the extended class. I'm wanting the constructor of the extended class to run only once.
I know this isn't right but something like this:
<?php
$oApp = new app;
class a extends $oApp {}
class b extends $oApp {}
Solution
Ah, in that case I believe you would want to pass the class in as a parameter for 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);
OTHER TIPS
What you want is this:
<?php
$oApp = new app;
class a extends app{}
class b extends app{}
If you have __constructor
s in the child classes, make sure that they call parent::__constructor
, otherwise they will probably not work properly.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow