0

Code:

class A {
    public $arrayToReturn = array();
    function __construct() {
        $arrayToReturn['country'] = 'US';
    }
}
class B extends A {
    public function foo() {
        print_r($arrayToReturn);
   }
}
$b = new B();
$b->foo();
print_r($b->arrayToReturn);

Result:

PHP Notice:  Undefined variable: arrayToReturn in xxxx.php on line 11
Array
(
)

I cannot get array in functions of class B, and get an empty array which should has one element by $b->arrayToReturn call. Why?

sxlllslgh
  • 11
  • 4
  • flagged as "why this code is not working". please give more details. – Alexandre Martin Aug 19 '16 at 18:26
  • and then of course, also dupe of http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and – Marc B Aug 19 '16 at 18:29

1 Answers1

3

You have to use $this->arrayToReturn:

class B extends A {
    public function foo() {
        print_r($this->arrayToReturn);
   }
}

Same in class A:

class A {
    public $arrayToReturn = array();
    function __construct() {
        $this->arrayToReturn['country'] = 'US';
    }
}
pavlovich
  • 1,935
  • 15
  • 20