Perlessence

Handling arrays in a static class

June 17, 2007 00:42

I'm creating a class to manage layout configuration on my site. It does things like set the page title, site name, includes JavaScript and CSS files, etc. This is modeled after Gaia's LayoutManager class, but much simpler because it doesn't have Gaia's site-specific stuff in it. Like Gaia's LayoutManager, it is a static class, all public methods and properties are static; this allows the class to manage site stuff without carrying an instance around. However, there is one big problem: PHP evidently doesn't know how to handle class properties that are arrays when called in a static context.

Finally, I solved the problem using a variation on Gaia's solution. I created a separate data container class that holds all the information. Then, each setter calls a method in the LayoutManager class that checks if a static class property is an instance of the LayoutManagerContainer and if not, creates an instance of the container class and stores it in the static class property; either way, the container object is returned. Then I can access the properties I want directly within the class. To get the data container values from outside the LayoutManager, I wrote a getter method that takes a parameter name and returns the appropriate value from the stored data container.

class Foo {

    private static $data;

    public static function addToArray($var) {
        $data = self::data();
        $data->my_array[] = $var;
    }

    private function data() {
        if (!is_a(self::$data, 'FooContainer')) {
            self::$data = new FooContainer();
        }
        return self::$data;
    }

    public static function get($param) {
        $data = self::data();
        if (property_exists(self::$data, $var)) {
            return $data->$var;
        }
    }

}

class FooContainer {
    public my_array = array();
}

Foo::addToArray('hello');
Foo::addToArray('goodbye');
$data = Foo::get('my_array'); // $data = array('hello', 'goodbye');
© Probably a million other people from whom I've subconsciously stolen this layout. Also, Karen Ziv (me). Don't steal my stuff.