julio
julio

Reputation: 6728

setting PHP class variables

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.

Upvotes: 1

Views: 2486

Answers (2)

NullUserException
NullUserException

Reputation: 85458

It looks like you're very confused with inheritance and OOP. This is not at all how it works.

I want to simply set a variable in the calling (parent) class from a child class.

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.

parent::setVar('yoyo!');

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().

Upvotes: 6

konsolenfreddy
konsolenfreddy

Reputation: 9671

Well, with

$temp = new test2();

you are creating a new instance of that class. They are not related anymore.

Inheritance only influences an individual instance of a class hierarchy.

Upvotes: 5

Related Questions