php5: arrays, stdClass and best practice

php5.2+ is all about objects and a maturing OOP language. Up until now the reliable method to structure an associative list of items is by using an array

CODE:
  1. $arA = new array();
  2. $arA['one'] = 1;
  3. $arA['two'] = array('one','two');
  4. $arA['three'] = 'three';

All well and good. Nothing earth shattering there.

With php5's changed object model and the passing of objects by reference, as well as the ability to type-hint function arguments - and in php6 function returns - the power of objects as data holders is more integral to best practices.

CODE:
  1. $stA = new stdClass;
  2. $stA->one = 1;
  3. $stA->two = array('one','two');
  4. $stA->three = 'three';
  5.  
  6. //type-hint forcing
  7. function passStd(stdClass $std) {
  8.    //do stuff...
  9. }

Again, not-earth shattering, but neater (IMO) and better OOP practice. I'm sure there are many opinions on this as well as a much deeper usages - e.g with SPL.

I've not done any baseline testing for speed differences. Maybe someone with knowledge (and time!) has the info.

Test

Leave a Reply