Link to home
Create AccountLog in
Avatar of pixalax
pixalaxFlag for Poland

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;
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;
		}

Open in new window


 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;

Open in new window


 How could I solve this problem? Thank you for your help and concern in advance.
Avatar of mydropz
mydropz

if (property_exists($this, $key)) {
						$$this->$key = $value;
					}

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
Avatar of pixalax

ASKER

If I don't it gives error saying that I can't use $this
$this is a reserved word.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
use something else rhan $this maybe you could use $that add it to te beginning of the function like
$that='';

Open in new window

Avatar of pixalax

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.