[thelist] PHP object property getters/setters

Chris Johnston fuzzylizard at gmail.com
Wed Nov 30 17:07:04 CST 2005


On 11/30/05, Andrew Kamm <akamm at demicooper.com> wrote:
>
>
>
>
> //State name:
> echo $cust->state->stateName;
>
> //State ID:
> echo $cust->state->stateID;


The above would be a bad way of doing things.

$cust = new customer( $id );
>
> $state = $cust->state;
>
> //State name:
> echo $state->stateName;


This would be a better way of doing things.

I am not familiar with php, but in general, when you are doing OO you want
to follow the design pattern that states -- only talk to your friends. This
means that you only talk to objects that you have direct references to. So
chaining calls together is generally a bad thing. This would be the first
example above that I labelled as bad.

So, in order to talk to embedded objects, you would first get that
object--in order to setup a reference to it--and then talk to that object
directly. This is what you have done in the second example.

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)?
>
>
However, if you find that you have a lot of objects inside objects, then I
would say you really need to take another look at your design. There are
definitely ways you can simplify things and detach a lot of those objects or
simplify them.

Also look at why you have objects inside of objects. What is the logical
reason that object A is embedded inside of Object B. This is an
association--i.e., a uses, or contains, or has a relation. In other words,
object B uses object A or object B contains object A or object B has a
object A and there should be a logical reason for each of these
relationships. If there is no logical reason for creating an association,
then those two classes should be decoupled.

Hope that helps,

Chris

--
www.fuzzylizard.com



More information about the thelist mailing list