Reputation: 1131
What I would like to do is chain a few classes together using "extends". It kinda works, but not like I expected it to. So I must be doing something wrong.
From what I gathered, when you extend a class you inherit all of its properties. So with that in mind I like to make my config file available in all classes. To do this I want to extend all classes on an autoLoader class. This seems logical to me, but correct me if I'm wrong.
I have two classes
AutoLoader
Class AutoLoader {
public $oConf = null;
public function __construct($oConfig) {
$this->$oConf = $oConfig;
}
public function getConf() {
return $this->$oConf;
}
}
other class
Class foo extends AutoLoader {
public function bar() {
var_dump($this->getConf());
}
}
My question is, why is the var_dump NULL.
It is strange to me cause this always returns the conf:
$autoLoader = new AutoLoader($array);
var_dump($autoLoader->getConf());
What am I missing here.
Upvotes: 0
Views: 80
Reputation: 19
You should create instance of foo
class and give into constructor your config variable:
$config = 'My_config';
$foo = new foo($config);
$foo->bar();
Will output:
(string) "My_config"
Upvotes: 1
Reputation: 522165
You are extending and inheriting the class structure, not the object instance.
Just take this code as an example:
$foo = new Foo('foo');
$bar = new Foo;
Would you expect $bar
to have access to the argument 'foo'
passed into the first object somehow? No. Extension doesn't change that.
You should be using composition or dependency injection (e.g. pass an autoloader into the constructor of Foo
). Don't make Foo
an Autoloader
, give it an Autoloader
if it needs one. When you extend a class, that new class is also its parent class. That means it could be used in place of the parent class. Anywhere you'd use an Autoloader
class, you could substitute Foo
instead. Does that make sense? Is Foo
an Autoloader
? Does $foo instanceof Autoloader == true
make any sense? No.
Upvotes: 4
Reputation: 1399
If inheriting class have an own constructor, you are probably not passing the oConfig to the parenting class (Autoloader) in the case.
also, your constructor expects an config.
So you should be doing this in your child constructor if you don't have one:
function __construct($oConfig) {
parent::__construct($oConfig);
// rest of your constructor code here
}
Upvotes: 1