PHP – dynamic vars in classes

As I’m all about python, and pythonic is the way I speak any coding language, I had a challenge in finding a way to dynamically implement new variables in a class.

Unlike python, in which this is very simply done by:

class MyClass:
    def __init__(self):
        self.newvar = 'value'
        self.newvar2 = 'bla'

It’s quite the challenge doing something similar in PHP. In fact, even after finding a partial solution, it’s plain _impossible_…
One way, though, to make it seem like you succeeded in that fact, is by using the __get and __set function definitions in PHP. Quite similar to __getitem__ and __setitem__ in python. Especially in its implementation.

The solution

Now, as to explain whatever I was brabbling earlier into clear, simple code, and testing code:

class MyExplainerClass {
    private $data;

    public function MyExplainerClass() {
        $this -> data = array(); // Initialization
    }

    public __get($name) {
        if (array_key_exists($name, $this -> data))
            return $this -> data[$name];
        // Here you can put debugging, error showing, etc...
    }

    public __set($name, $value) {
        $this -> data[$name] = $value;
    }
}

$myTester = new MyExplainerClass();
$myTester -> newvar = 'value';
echo $myTester -> newvar; // value

Now, that’s about everything here to explain. I think it’s clear enough for even the simpelest out there.

Share and Enjoy:
  • Print
  • Reddit
  • Identi.ca
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Slashdot

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.