3

I have a superclass which contains properties & methods for setting them

class Super{
    private $property;

    function __construct($set){
        $this->property = $set;
    }
}

then I have a subclass that needs to use that property

class Sub extends Super{
    private $sub_property

    function __construct(){
        parent::__construct();
        $this->sub_property = $this->property;
    }
}

but I keep getting an error

Notice: Undefined property: Sub::$property in sub.php on line 7

where am I going wrong?

1
  • 2
    (tip) Since this is your second question about basic OOP features in PHP today, I suggest to have a look at the chapter Classes and Objects in the PHP Manual. Commented Jan 21, 2011 at 16:32

3 Answers 3

8

The error is saying that it's trying to find a local variable called $property which doesn't exist.

To refer to $property in object context, as you intended, you need $this and the arrow.

$this->sub_property = $this->property;

secondly, the line above will fail as is because $property is private to the Super class. Make it protected instead, so it's inherited.

protected $property;

Third, (thanks Merijn, I missed this), Sub needs to extend Super.

class Sub extends Super
Sign up to request clarification or add additional context in comments.

1 Comment

It is very confusing if you edit your question like that. In future, please just accept the answer or edit your question but add new code that shows your solution.
3

You need to make your $sub_property protected instead of private.

Comments

2

You'll also need to specify that the subclass extends from the superclass:

class Sub extends Super {
   // code
}

1 Comment

my bad, it is already like that in the code, have edited question to reflect this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.