Search code examples
phpclassinheritanceextend

getting value from a class that instantiated current class


I am really sorry if this is s dumb question and I'm having a brain fart, this just seems like something I should know. If I have a structure similar to below, is there some way to get $fooVar in Class bar. Do I need to find some way to pass $fooVar as a parameter or is there some inheritance there that I can take advantage of? I'd like to avoid passing it as a parameter if at all possible. Class bar extends another class and if I passed t as a parameter I'd have to do some extra work.

Thanks so much for your help.

Class foo{
    $fooVar;
    $bar = new bar()
}//end foo{}
Class bar extends AnotherClass{
    echo $foo->fooVar;
}//end bar{}

Solution

  • First of all I want to say, I just know a bit about php but I think this problem can be adapted to any other OOP based language. So I tried to put some code for you up. Their are 4 different approaches I am aware of. (I want to consider that I didn't test the below code snippets.)

    1. Declare a get-Function

    in your superclass to access the value of $fooVar. This has the positiv effect to access the value from any other class which can call the get-function.
    Like this:

        Class foo{
          private $fooVar;
    
          function __construct() {
            $bar = new bar();
          }
    
          function getFooVar() {
            return $fooVar;
          }
        }
        Class bar extends foo{
          function __construct() {
            private $foo = parent::getFooVar(); //init $foo on instantiation by get-function
          }
        }
    

    2.

    Declare $fooVar as protected

    the make $fooVar only accessible by their subclasses.

        Class foo{
          protected $fooVar;
    
          function __construct() {
            $bar = new bar();
          }
        }
        Class bar extends foo{
          function __construct() {
            private $foo = parent::$fooVar; //init $foo on instantiation by parent
          }
        }
    

    3. Add $fooVar as parameter

    to your subclass constructor. (I am fully aware of that this is not what you want, but I state it here as another solution and for clarification.)

        Class foo{
          protected $fooVar;
    
          function __construct() {
            $bar = new bar($fooVar);
          }
        }
        Class bar extends foo{
          function __construct($var) {
            private $foo = $var; //init $foo on instantiation with parameter
          }
        }
    

    4.

    Make $fooVar global.

    (another solution but not recommanded.)

    I think you are going well with the get function. From the last two cases I would advice especially against the last one.

    I really hope this is what you are looking for and it helps alot.