Sticky Posts
May 24, 2009
PHP Objects With Case-Insensitive Variables
I really hate it when I create a new stdClass and do this: $obj->Var = 1; echo $obj->var; Notice the V and v. This will fail as class variables are case sensitive and ->var does not exist. Functions are case insensitive in PHP but variables are not ... thing I consider peculiar. I understand case sensitivity (I write C++) but if you remove it from functions remove it from variables also.
I had to create a new object skeleton to handle this problem. I work with a lot of objects (I like them better than arrays most of time) and I'm not always sure of the proper casing of a variable, especially when I get it from elsewhere (a query string ...). So I need both $obj->Var = 1; echo $obj->var; to work the same way.
To cast an array to this new object don't use $obj = (object)array('key'=>'value'); but use $obj = new obj(array('key'=>'value'));. With obj objects, ->Key or ->KEY or ->key work. This made my life a lot easier and this is the object for your use.
Registration is quick, painless and worth its weight in gold.
Enjoy this as I really do! It needs PHP 5+.
PS: If you use this on an array with numeric keys a _ is prepended. So $obj = obj(array(1, 2, 3)); echo $obj->_0; echo $obj->_1; echo $obj->_2;

