Broshi Broshi - 26 days ago 6
PHP Question

PHP Class with properties that has objects be accessible to these objects

I have a main php class such as this:

class MyClass {
public $a;
public $b;

function __construct()
{
$this->a = new \SomeClass();
$this->b = 'some string';
}
}


is there a way the class which is stored in the
$a
(
SomeClass
) property can access the
$b
value which is actually a property which is stored in the class that initiated
$a
(
MyClass
) ?

Answer

You could do something like this:

class MyClass {
    public $a;
    public $b;

    function __construct()
    {
      $this->a = new \SomeClass($this);
      $this->b = 'some string';
    }
}

class SomeClass {
    public $mc;

    function __construct(MyClass $mc)
    {
      $this->mc = $mc;
    }
}

$myClass = new MyClass();
echo $myClass->a->mc->b;

The output would be: some string

Comments