[development] Drupal - to use objects or arrays

Doug Green douggreen at douggreenconsulting.com
Wed Jan 10 13:07:45 UTC 2007


>From Khalid B:

> I think Doug is taking about PHP objects, not objects as they are used in
core Drupal.

 

I wasn't referring to full OOP objects (those with functions and
inheritance).  I am mostly referring to objects as data storage and the
php4/php5 language syntactical differences (and php4 mishandling).

 

For example, the following code snippet in php5:

 

  $someobject = new stdClass;

  $someobjectarray[$someobjectkey] = $someobject;

  $someobject->element = 'something'; // modifies object in array

 

Must be the following in php4:

 

  $someobject =& new stdClass;

  $someobjectarray[$someobjectkey] =& $someobject;

  $someobject->element = 'something'; // modifies object in array

 

You must make sure all object assignments are done with =& and instead of =.
(I'm not certain of the assignment of the object instantiation, but the
CiviCRM folks say it is needed.)

 

And then the problem with loops in php5:

 

  Foreach ($someobjectarray as $someobject) {

    $someobject->element = 'something'; // modifies original object

  }

 

Is really shorthand for:

  Foreach ($someobjectarray as &$someobject) {

    $someobject->element = 'something'; // modifies original object

  }

 

But php4 doesn't support either, so in php4, you must write:

 

  Foreach ($someobjectarray as $someobjectkey => $someobjectreadonly) {

    $someobjectreadonly->element = 'something'; // modifies w/I loop

    $someobject =& $someobjectarray[$someobjectkey];

    $someobject->element = 'something'; // modifies original object

  }

 

There are a few other idiosyncrasies.  See also:

 

 
http://wiki.civicrm.org/confluence/display/CRM/Writing+PHP4+Compatible+code

 

I'm probably going to rip them out of the releasemonitor project
(http://cvs.drupal.org/viewcvs/drupal/contributions/modules/releasemonitor/)
and just use arrays.  I'm hearing some feedback that others agree and that
there is no advantage to objects, and that there may actually be a
disadvantage to using them!

 

>From Larry Garfield:

> I think the general guideline is "use what makes semantic sense at the
time".

 

IMHO, objects make "semantic" sense most of the time, but php4 makes them
impractical.

 

Doug Green

www.civicactions.com

www.douggreenconsulting.com

 

Changing the world one node at a time!

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.drupal.org/pipermail/development/attachments/20070110/17d1ba86/attachment.htm 


More information about the development mailing list