rawkes - 27 March 2007 04:42 PM
Could you give me an example of how you would do it?
class Dog {
var $color = '';
function set_color($color) {
$this->color = $color;
}
}
You may choose to change the internal name of the “color” property to something else, and update the method, but the interface would remain consistent…. you’d still call $this->dog->set_color(‘red’); regardless of the internal variable name.
Again, just guidelines… depending on the complexity of your classes, or who is going to be implementing them, you may want to use methods for both “setting” and “getting” variables. In my own code, I just access properties directly because I know exactly how they’re going to be implemented.
There’s no hand-and-fast rules, just recommended ways. My recommendation: start by using methods, and then as you get more comfortable, you can begin to access properties directly. Methods are definitely safer.
You can even create generic methods:
class Dog {
var $color = '';
function set($k, $v) {
if (isset($this->$k)) {
$this->$k = $v;
}
}
function get($k) {
if (isset($this->$k)) {
return $this->$k;
}
}
}
In the above code, I created generic get() and set() methods that both checked if a variable existed first. This is a good way to ensure that code changes won’t break your application and generate errors.