I'm trying to switch to OOP way of programming in PHP. I'm running into the issues with multiple children and one single parent classes.
In my parent's construct method I include a child class file with include() method and then create a variable referencing the child class like so:
class App {
function __construct() {
include_once('childClass.php');
$this->childvar = new childClass;
include_once('childClass2.php');
$this->childvar2 = new childClass2;
}
}
And my child classes are as follows:
class childClass extends App {
var test = 1;
function __construct() {
}
}
class childClass2 extends App {
function __construct() {
echo $this->childvar->test;
}
}
When I try to access a childClass vriable from childClass2 I get an error
Undefined property: childClass2::$test
What am I doing wrong here?
If you want to use the constructor of App
in childClass2
make sure you call parent::__construct();
first.
class childClass2 extends App {
function __construct() {
parent::__construct();
echo $this->childvar->test;
}
}
Keep in mind that as it is this will create an infinite loop.
In general it is not common to see a new
call in a constructor. Any dependencies should be passed in. This incidentally also deals with the infinite loop. Your current design has more problems though.
class App {
function __construct($child1, $child2) {
$this->child1 = $child1;
$this->child2 = $child2;
}
}
class childClass extends App {
var test = 1;
function __construct($child1, $child2) {
parent::__construct($child1, $child2);
}
}
class childClass2 extends App {
function __construct($child1, $child2) {
parent::__construct($child1, $child2);
echo $this->childvar->test; // error childvar is null
}
}
$app = new App(new childClass(null, null), new childClass2(null, null));