Greg Aker

var_dump($this) in EE/CI with no recursion

Filed in: PHP, ExpressionEngine, CodeIgniter

August 18, 2011

Here's a quick little tip for all you EE addon developers out there. I've seen some people moaning on Twitter about how a var_dump() can be hard on the browser due to the recursion in the CodeIgniter singleton. So check how I like to roll in my CI libraries/EE addons.

<?php

class Foo {

    protected $_foo;

    public function __construct()
    {
        $this->_foo = $this->config->item('something');
    }
}

Look maw, no $this->CI

Did you know you you can do this in a CodeIgniter library or an ExpressionEngine mcp/mod/extension/plugin/accessory file? It's pretty easy to accomplish, and if you know the CI internals you'll know that the CI_Model class already does this. Actually, that's all it does!

<?php

class Foo {

    protected $_foo;

    public function __construct()
    {
        $this->_foo = $this->config->item('something');
    }

    // ------------------------------------------------------------

    public function __get($key)
    {
        $CI =& get_instance();
        return $CI->$key;
    }   
}

So then where you call your library, code like this:

<?php

$this->load->library('foo');

var_dump($this->foo);

Will not include anything from the CI Super Object. yay! If you want to get really sneaky, have your class extend CI_Model. However, I think that would look really weird.

I'm not advocating doing this in your addons that you distribute, but I want to illustrate that if you develop with a platform, it totally pays to get down and dirty with the internals.