1

For an instance, I have classes like this:

class MyClassA{
   protected $variableA='this is var A';
   public $variableB='this is var B';
   //some function here
}

class MyClassB extends MyClassA{
   //some function here
}

class MyClassC extends MyClassB{
   //some function here
}

class MyClassD extends MyClassC{
   //some function here
}

How can I get $variableA and $variableB from MyClassD?

3 Answers 3

3

Just reference them in any class using $this.

class MyClassD extends MyClassC {
    function __construct()
    {
        echo $this->variableA; 
        echo $this->variableB;
    }
}

$var = new MyClassD;

See it work!

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

Comments

1

Since variableA is public in the base class, you can just access it directly like so: $MyClassDObj->variableB.

Since variableA is protected, you need to write a getter if you wanted to access it from outside the class, otherwise from within class D, you can access it just like variableB. A getter would look like this:

public function getVariableA()
{
    return $this->variableA;
}

And then you call $MyClassDObj->getVariableA();

6 Comments

If variableA were private, you'd need a getter. protected does not require a getter.
Protected is the same as private except that protected variables are accessible from derived classes, private variables are not, therefore it still requires a getter for access outside the class. php.net/manual/en/language.oop5.visibility.php
Drew, unfortunately you are mistaken. See my example, no getter required.
I know that, but I said if he wanted to access it from outside the class he would need a getter. He didn't really clarify in the question. Sorry if I didn't make that clear.
OH! My mistake. Then of course you are correct! Referencing these protected variables from outside of the class requires a getter. Sorry.
|
0

Just like you'd get it from MyClassA.

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.