开发者

Variable scope problem with super object

I'm having some trouble creating a "super object" (similar to that of CodeIgniter) for a framework project I'm working on.

I want to make a super object that all of my other classes will run through. I did that, but it seems I am unable to use my super object's object in each of my classes without using the global keyword in every function.

I have something like this:

class a
{
    function aa()
    {
        return 'class a';
    }
}

class b
{
    function bb()
    {
        $blah->a->aa();
    }
}

class superobj
{
    function loadClass($class)
    {
       开发者_开发知识库 $this->$class = new $class;
    }
}

class blah extends superobj
{
    function __construct()
    {
        $this->loadClass('a');
        $this->loadClass('b');
    }
}

$blah = new $blah;

So if I run this, I get an error because I can't access the aa method. If I put global $blah into the method bb, then it works (or at least in my real project it does, I dunno about this 5 second mockup hehe).

So is there any way to either make the $blah object global so that I don't need to reference it for every method, OR is there a better way to achieve what I am trying to do?

I'm not very good at OOP...


function bb() {
    $blah->a->aa();
}

Indeed, as with any function, this function has no variables in its scope. $blah was neither passed to the function nor is it defined in the function, so it doesn't exist.

If your objects depend on an instance of blah to work, you should pass it to the constructor.

class b {

    var $blah = null;

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

    function bb() {
        $this->blah->foo();
    }
}

$b = new b($instanceOfBlah);

Alternatively, use a static class that holds references to global objects and returns them on request (Registry pattern, like $blah = Registry::get('blah')).

Don't use global. Just don't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜