Moin!
When I played with ruby I found some nice features of the language that I’d really like to see in php as well but apparently most of the syntactic sugar is not part of php5 at all. However, due to that you will often see classes with get and setter methods that basically do nothing special. In your getter and setter methods you can work on the data passed around which is very useful if you change this unique logic at some point later in the applications lifetime when you don’t want to change too much in your interface.
In my ruby quickstart I wrote about classes and how you can write short properties getters and setters.
class Car
attr_accessor :mileage
def initialize(mileage)
@mileage = mileage
end
end
audi = Car.new(245000)
puts "old mileage: "+audi.mileage.to_s
audi.mileage = 246000
puts "new mileage: "+audi.mileage.to_s
In php5 there is no such thing like “attr_accessor” but you can at least try to build something similar which is not too bad at all:
I first tried to replicate it 1:1 but it doesn’t work of course :). Look!
class Car {
private $mileage = 123000;
function mileage($newMileage=0) {
if ($newMileage>0) {
$this->mileage = $newMileage;
} else {
return $this->mileage;
}
}
}
$mycar = new Car;
print $mycar->mileage;
$mycar->mileage = 124000;
print $mycar->mileage;
This doesn’t work and throws “Fatal error: Cannot access private property Car::$mileage”. Sure, “mileage” is a private property of class “Car” so you can’t access it and I didn’t wanted to access it. I wanted to use the method like a property…no sir!
The best solution I came up with so far is the following:
class Car {
private $mileage = 123000;
function mileage($newMileage=0) {
if ($newMileage>0) {
$this->mileage = $newMileage;
} else {
return $this->mileage;
}
}
}
$mycar = new Car;
print $mycar->mileage(); // 123000
$mycar->mileage(124000);
print $mycar->mileage(); // 124000
This way I really lose all the verbose get and setter methods that many books teach you to write. This way you can still work on the data you pass, it’s shorter and using it in your code is by far more readable and it makes more sense.
Tell me if you disagree :). I really prefer it that way!
Andreas Schipplock.


