0

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?

1 Answer 1

3

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.

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

7 Comments

It looks like you have an infinite regress. The Foo constructor creates Bar, and the Bar constructor tries to access the properties of $foo. But $foo won't have a value until the Foo constructor returns.
you use gobal keyword but its also won't work. What if I use $this instead of $foo???
Nothing will work. You're trying to access something before it's finished constructing.
agreed with @user2727841, use of global does not work, but I can pass itself into the constructor $this->bar = new Bar($this); I do prefer that. +1
But you won't be able to access $foo->myProperty, because the constructor doesn't assign that until after it call new Bar($this).
|

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.