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?

Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
  • 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](http://de2.php.net/manual/en/language.oop5.php). – Gordon Jan 21 '11 at 16:32

3 Answers3

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
Tesserex
  • 17,166
  • 5
  • 66
  • 106
  • 2
    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. – Gregory Jun 14 '17 at 11:31
3

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

jb1785
  • 722
  • 1
  • 7
  • 19
2

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

class Sub extends Super {
   // code
}
mrbellek
  • 2,300
  • 16
  • 20