Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php automated setter and getter

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?

like image 715
sebataz Avatar asked Jan 05 '12 13:01

sebataz


2 Answers

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.

like image 138
mario Avatar answered Sep 30 '22 13:09

mario


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

read this

like image 39
Dau Avatar answered Sep 30 '22 14:09

Dau