简体   繁体   中英

turning variable into class variable

In my PHP class I have

public $a;
public $b;
public $c;
public $d;

and I set there values in the construct.

I am now attempting to write a update function, and i'm trying to check if they are updating, say $a, to be the same as it is.

function update($what, $to) {

     if ($to == $this->what) return false;
     ...
}

$updated = $instance->update($a, "Foobar");
if ($updated) echo "Updated";
else echo "You didn't change the value";

but since I know this line

         if ($to == $this->what) return false;

is invalid, i'm seeking a new way to write it.

Ideas?

Thanks in advance

The solution to your dilemma are variable variables. Your update function must assign it like this:

 $this->{$what} = $to;

The if-check would be correspondingly:

 if ($to == $this->{$what}) return false;

And you cannot actually invoke the update() method with a variable $a . You must give it a variable name as string:

 $instance->update("a", "Foobar");

You can do something like:

if ($to == $this->$what) return false;

And call it like this:

update("a", "Foobar");

This uses variable variables ( http://php.net/manual/en/language.variables.variable.php ).


You could also pass by reference:

function update(&$what, $to) {
     if ($to == $what) return false;
        ...
}

And call it like you did in your example.

$this->$what should do the trick, if $what = 'a'

You generally want to avoid doing that though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM