0

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!

1
  • 2
    Your attributes are private, make them protected or public. Commented Sep 12, 2013 at 19:33

2 Answers 2

4

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.

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

3 Comments

Thank you for your quick response! I'll mark your answer, but currently there is a 7 minute limit.
Just complementing @Sven's answer with further reading for better understanding of methods/properties visibility in OOP: php.net/manual/en/language.oop5.visibility.php
I suppose I'm willing to concede that although Sven and I said pretty much exactly the same thing at the same time, he said it better than I did.
2

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.

Comments

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.