[thelist] PHP object property getters/setters

Andrew Kamm akamm at demicooper.com
Wed Nov 30 09:19:26 CST 2005



I've started working with PHP5 OOP, and I'm trying to find the best practice
for accessing properties of objects within an object. I understand the
getter/setter concept of using a method such as $person->getName() rather
than allowing public access to $person->name, but what if the property being
stored in the object is an object with it's own properties - how do I access
those properties with out making a mess of code? As an example:

In a class called "customer", the customer has a state property, which is:

public $state; //object

Before attempting to use getters/setters, I could access the whatever info I
needed about the state pretty easily:

$cust = new customer( $id );

//State name:
echo $cust->state->stateName;

//State ID:
echo $cust->state->stateID;

//State abbreviation:
echo $cust->state->stateAbbr;

So, now that I'm using the getter/setter concept, it seems I'll need to
either make getter/setters for each property of each object within each
object (which sounds worse than allowing public access to the variables) or
setup objects outside of the class that is using them when I need to access:

$cust = new customer( $id );

$state = $cust->state;

//State name:
echo $state->stateName;

Not a huge deal until things start expanding to objects within objects,
within objects, etc.

So - since I'm not in love with these prospects and they all seem to require
a bit of extra code, what's the "best practice" way of doing this (or is
there a way to do this that I'm missing)?

Is there anything that would work similar to this non-functional, but
oh-so-desireable syntax:

$cust->getState()->stateName; //won't call the state name :(

thanks! 





More information about the thelist mailing list