[thelist] basic OO php question

Brooking, John John.Brooking at sappi.com
Thu Apr 19 12:44:52 CDT 2007


> From: "Rick den Haan" <rick.denhaan at gmail.com>
>
> If I call a class (Y) from within another class (X), is it possible to
> access properties of X from within Y without have Y extend X?

If you are using PHP5, class members can be public, among other
scopes[0]. So in your example, instead of

   var $foo = "bar";

inside of class X, use

   public $foo = "bar";
   
Then this code:

   x = new X();
   echo $x->foo;
   
outputs "bar", as you want. Note that you still need to instantiate an
object of class of X. Alternately, if the value of $foo will never
change, you can declare it as a class constant[1] and access it as
X::foo with having to instantiate it.

Note that it's considered better OO practice to have private members
that can be read and changed by accessor functions than to have pubic
members, but that's what you asked. The accessor function method
protects the data better, which is one of the goals of the OO style.

[0] http://www.php.net/manual/en/language.oop5.visibility.php
[1] http://www.php.net/manual/en/language.oop5.constants.php
   
- John
-- 


This message may contain information which is private, privileged or confidential and is intended solely for the use of the individual or entity named in the message. If you are not the intended recipient of this message, please notify the sender thereof and destroy / delete the message. Neither the sender nor Sappi Limited (including its subsidiaries and associated companies) shall incur any liability resulting directly or indirectly from accessing any of the attached files which may contain a virus or the like.




More information about the thelist mailing list