pixalax
asked on
how to create Auto Setter method in PHP?
Hello all,
I would like to create auto setters. What I would like to do is pass an object to class method and it will set all class variables to passed object values (if class variable exits)
Something like;
But this code doesn't work. When I try to echo just shows a blank page because it is not set.
How could I solve this problem? Thank you for your help and concern in advance.
I would like to create auto setters. What I would like to do is pass an object to class method and it will set all class variables to passed object values (if class variable exits)
Something like;
public static function setter ($object=NULL) {
if (is_object($object)) {
foreach ($object as $key => $value) {
if (property_exists($this, $key)) {
$$this->$key = $value;
}
}
return $this;
}
But this code doesn't work. When I try to echo just shows a blank page because it is not set.
echo $class->class_var;
How could I solve this problem? Thank you for your help and concern in advance.
ASKER
If I don't it gives error saying that I can't use $this
$this is a reserved word.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
use something else rhan $this maybe you could use $that add it to te beginning of the function like
$that='';
ASKER
Thank you, instead of going to deal and fight over class variables, I just made an array of them and assigned values to them.
This is making coding lines a bit longer but it is a solution in the end.
This is making coding lines a bit longer but it is a solution in the end.
Open in new window
why do you use double dolar sign for this?i think that creates the problem because double dollar sign doesn't set the value but treats the value as the name of the variable so $this will stay empty