I’m trying to get a handle on using OOP with PHP, and I’m a little stumped with some of the class inheritance stuff.
Here’s a couple simple classes I’m using to try to learn the way these work. I want to simply set a variable in the calling (parent) class from a child class. From the examples I’ve read it seems like this should work, but the sub class fails to set the parent variable:
class test {
private $myvar;
private $temp;
function __construct(){
$this->myvar = 'yo!';
$temp = new test2();
$temp->tester();
echo $this->myvar;
}
public function setVar($in){
$this->myvar = $in;
}
}
class test2 extends test{
function __construct(){
}
public function tester(){
parent::setVar('yoyo!');
}
}
$inst = new test(); // expecting 'yoyo!' but returning 'yo!'
Thanks for any help.
It looks like you’re very confused with inheritance and OOP. This is not at all how it works.
This is not possible, for a several reasons.
First of all, when you use
new, it creates a new instance of the class. Each instance is independent from each other, in the sense that their properties won’t be tied together.Also when you have a child class, it inherits properties and methods from the parent. But when you create an instance of it, it’s an instance of the child class – not the parent class. I don’t what you want to accomplish there.
The nice thing about inheritance is that you get the parent’s methods by default, unless you override them in the child class. Since you aren’t doing that, there’s no need to use
parent::setVar(), just do$this->setvar().