9

I'm trying to implement some automated getter and setter for php objects.

My target is to automatically have for each properties the methods getProperty() and setProperty(value), that way if the method is not implemented for a property the script will simply set or get the value.

An example, to make myself clear:

class Foo {
    public $Bar;
}

$A = new A();
$A->setBar("bar");
$A->getBar(); // -> output "bar"

or

class Foo {
    public $Bar;
    public function setBar($bar) { $Bar = $bar; }
    public function getBar($bar) { return 'the value is: ' . $bar; }
}

$A = new A();
$A->setBar("bar");
$A->getBar(); // -> output "the value is: bar"

Any idea/hints on how to accomplish this?

sebataz
  • 1,025
  • 2
  • 11
  • 35
  • just a shot in the field: How about you parse the document and write setters and getters with an output writer for every found property. I'd further recommend to search for Frameworks who already can do this. Other Platforms can do it even with automated persistance (e.g. Grails for the Java Platform) – 最白目 Jan 05 '12 at 13:10

2 Answers2

26

If you want to simulate the getXy and setXy functions for arbitrary properties, then use the magic __call wrapper:

function __call($method, $params) {

     $var = lcfirst(substr($method, 3));

     if (strncasecmp($method, "get", 3) === 0) {
         return $this->$var;
     }
     if (strncasecmp($method, "set", 3) === 0) {
         $this->$var = $params[0];
     }
}

This would be a good opportunity to do something useful for once, by adding a typemap or anything. Otherwise eschewing getters and setters alltogether might be advisable.

mario
  • 144,265
  • 20
  • 237
  • 291
3

read the magic functions of php and your need you can use __get and __set functions

read this

Dau
  • 8,578
  • 4
  • 23
  • 48
  • that's not it. I need the trick the other way around. `__get` and `__set` are used when the property itself doesn't exist – sebataz Jan 05 '12 at 13:06
  • 2
    He did tell you to read about magic functions. Check what `__call` magic function does. – N.B. Jan 05 '12 at 13:09