I found a use for properties :)

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

I found a use for properties :)

Post by timvw »

Perhaps you still remember, but a while ago i asked myself (here): Do we really need properties?

At the time i considered properties to be syntactic sugar (and nothing more) for methods we would otherwise call GetX and SetX...

Earlier this week i figured out that properties actually can do something which methods can't do: They give you the power to replace a variable with the result of a method.

Eg: Originally Foo had a field $bar.. And now some business changes have occured and instead of using a simple value $bar you need to calculate it instead. So you would have to update all the places that use $myInstance->bar with $myInstance->GetBar()...

Well, properties give you the chance to actually leave the external code as is.. The only thing that you have to do is remove the $bar field.. and implement __get/__set so that they call GetBar/SetBar...
User avatar
julian_lp
Forum Contributor
Posts: 121
Joined: Sun Jul 09, 2006 1:00 am
Location: la plata - argentina

Post by julian_lp »

wouldn't be enough just never call a member field directly?

I mean, one never should call

$val = $obj->var_name;

instead, it'd be much more convenient doing

$val = $obj->Get_var_name();

I really work this way cause it seems to me very confusing not using parenthesis on an object call...
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

julian_lp wrote:wouldn't be enough just never call a member field directly?I mean, one never should call
$val = $obj->var_name;
The problem is that you don't always have control over code that was already written... Anyway, here's the situation which made me realise there was a good use for properties...

Code: Select all

public class BusinessParamters {
  public const int MyLimitation = 5;
}
As long as MyLimitation is a constant, it makes perfect sense not to wrap it in a function. But as i noticed, if the rules change it can be easily changed into:

Code: Select all

public class BusinessParameters {
 public static int MyLimitation {
  get {
    // calculate some things...
    return 10;
  }
 }
}
But perhaps properties are less useful for php... (Since __set and __get can't be static...)
Post Reply