tags:

views:

72

answers:

1

I have a PHP class that stores a complex multidimensional array, and rather than write individual accessor methods as an interface to this array I decided to use PHP5's __get method.

As I started to write these magic accessors it donned on me that I had no idea what best practices are here, so I thought I'd ask. Is one large if/else structure inside of __get() common?

I've included a small snippet of the class for reference:

<?php
   class Project {

      private $data; 

      public function __construct($d) {
         $this->data = $d;
      }

      public function __get($val) {
         if ($val === 'title')
            return $this->data['info']['projectName'];
         else if ($val === 'id')
            return $this->data['info']['projectID'];      
         else if ($val == 'health') {
            switch($this->data['info']['health']) {
               case 'OT':
               case 'NS':
               case 'LR':
                  return 'Low Risk&mdash;Healthy';
                  break;
               case 'CR':
                  return 'Critical Risk&mdash;Action Needed';
                  break;
               default:
                  return 'Unknown';            
            }
         }
      }
   }
?>

Then I'm just accessing the data like:

$o = new Project($array);
echo $o->title; #etc
A: 

In the end it is mostly an issue of alternatives. Therefore, I usually use the switch construct. Depending on the particular situation, regex can also be very useful.

txwikinger