Sunday, June 22, 2008

array to object

So I really get sick of:

if($promotion['req']['min'] > 10)

I love using multidimensional arrays for partitioning data/namespaces for the sake of sanity but the access is really quite.. icky. So I came up with a quick hack to turn a multidimensional array into an object so the above could be more like:

if($promotion->req->min > 10)

It saves a few characters and I think it becomes a LOT more readable as well as easier to comprehend especially on an oo level.

The code is simple/hackish:

class oArray{
/*class to turn a keyed array to object
IF a key is numeric it will be prepended with a letter n i.e. key 2 becomes n2
Really though this is meant for meaningful key=>val relationships
*/
function __construct($array){
foreach($array as $key=>$val){
$key = is_numeric($key) ? 'n'.$key : $key;
$this->$key = is_array($val) ? new oArray($val) : $val;
}
}
}
function oArray($array){
return new oArray($array);
}

You will notice that I have a function called oArray as well as a class which merely wraps the whole "$var = new object(params)" deal as that gets pretty repetitive. So Now I can do:

//instantiation
$promotion = oArray(Array(
'req'=>Array(
'min'=>50,
'max'=>100),
'grants'=>Array(
'limit'=>50,
'type'=>504))));

//access
if($promotion->req->min <= $promotion->grants->limit);
v.s.
if($promotion['req']['min'] <= $promotion['grants']['limit']);

This was all blatantly inspired by the way you can access objects in emcascript. I know that this is really a total abuse of php and oo design but when you are working with legacy systems sometimes you'll do anything to interject some semblance of sanity. Also I was listening to john zerzan lectures whilst I composed this. Maybe that explains why I would so something so meaningless; almost in opposition to his stance on technology.

Sunday, June 1, 2008

All is not quiet

So I have been working through project euler using my Hash class and some of its helpers and I am totally pleased with my results. A lot of my solutions are as short if not shorter than the python and ruby offerings. Saying that some of the later problems that don't relate to list comprehension are not aided by my Hash class but it's all the more reason to brush up on my math chops and extend the language in ways that CAN help with such problems. I would love to post some of my solutions on here but it's considered bad form to post them in public. I do want to be the first person to complete all of them in PHP as thus far no one has.