Reputation: 2128
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
Upvotes: 0
Views: 209
Reputation: 6621
$this->$what
should do the trick, if $what = 'a'
You generally want to avoid doing that though.
Upvotes: 0
Reputation: 145482
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");
Upvotes: 2
Reputation: 9857
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.
Upvotes: 1