Reputation: 9593
I have a class which is instantiated globally and in turn instantiates a second class from within its constructor. What I can't figure out is how to gain access to properties of the first class from the second.
<?php
class Foo
{
public $bar;
public $myProperty;
public function __construct()
{
$this->bar = new Bar();
$this->myProperty='hello';
}
}
class Bar
{
public function __construct()
{
echo $foo->myProperty; //I can't see that from here
}
}
$foo = new Foo();
?>
what might be the correct way of going about this?
Upvotes: 0
Views: 86
Reputation: 782755
You problem has nothing to do with scope of class properties, it's with scope of ordinary variables. $foo
is a global variable, so it's not normally visible inside functions. You need to do:
public function __construct()
{
global $foo;
echo $foo->myProperty;
}
However using global variables is usually bad form. It would be better if you passed $foo
as a parameter to the Bar
constructor.
Upvotes: 3