1

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.

2
  • 3
    It looks like you're very confused with inheritance and OOP. This is not at all how it works. Commented Apr 13, 2012 at 17:25
  • very is an understatement. I am trying to think of a metaphor on julio code to enable him to understand where he is going wrong. Work in progress ... Commented Apr 13, 2012 at 17:31

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

@NullUserException-- thanks for taking the time to make a clear answer. I think I understand. However, if for example the 'test2' class was not extending the 'test' class, but was still instantiated from within 'test'-- how would one access/modify the 'test' class' vars from within 'test2'? Is this possible?
@julio It is possible - you'd need the test2 instance to have a reference back to the test instance that instantiated it.
5

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.