None None
None None

Reputation: 547

PHP inheritance - methods and properties

I'm obviously not understanding inheritance correctly. I'll let my code do the talking:

abstract class Calc {
private $x;
private $y;
public function AddNumbers() {      
    echo $this->x. " + " .$this->y;
}
}

class myCalc extends Calc {
public function __construct ($x,$y) {
    $this->x = $x;
    $this->y = $y;
   }
}

$calc1 = new myCalc(3,4);
$calc1->AddNumbers();
echo 'done';
exit;

OK, so what's going on here: I'd like to have an abstract class, that would define two properties (x and y) and an abstract method, (nevermind the concatenation of numbers, implementation of the method is out of the scope of my question) which would access there properties.

Then, a concrete class extends that abstract one. As you can see, I can successfully access the properties and set them, but when I call add numbers, it appears as if the properties are not set.

What is going on, why is this not working and how can I fix it? I could just define a method for adding numbers in concrete class, but I want to have a method in abstract class with a definition that can be reused.

Thanks!

Upvotes: 0

Views: 49

Answers (2)

Sven
Sven

Reputation: 70853

The two properties in the abstract class are private, which means they are NOT present and known in any class that extends this one.

So MyCalc does not write to these properties, and you cannot read them in the AddNumbers function. The MyCalc constructor actually creates new, public properties instead.

Make the properties "protected", and it will work.

Upvotes: 4

meustrus
meustrus

Reputation: 7315

The private keyword defines that only the methods in Calc can modify those variables. If you want methods in Calc and methods in any of its subclasses to access those variables, use the protected keyword instead.

You can access $this->x because PHP will let you create a member variable on the object without declaring it. When you do this the resulting member variable is implicitly declared public but it doesn't relate to the private variable defined in Calc, which is not in scope in myCalc.

Upvotes: 2

Related Questions