Lenar Hoyt
Lenar Hoyt

Reputation: 6159

Is it possible to call a function when a variable changes in PHP?

function foo()
{ echo 'function called'; }

Is it possible to do something like this:

onchange($a, foo);
$a = "foo"; // echoes 'function called'
$a = "bar"; // echoes 'function called'

Instead of:

$a = "foo";
foo();      // echoes 'function called'
$a = "bar";
foo();      // echoes 'function called'

Upvotes: 0

Views: 58

Answers (2)

Joe
Joe

Reputation: 15802

Sort of. You can use what's called a setter, a function designed to set a variable.

function setFoo ($value)
{
    echo 'in setFoo';
    return $value;
}

$a = setFoo('foo'); // echoes 'in setFoo'
echo $a; // echoes 'foo'
$a = setFoo('bar'); // echoes 'in setFoo'
echo $a; // echoes 'bar'

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131871

In short: no. You shouldn't use global variables anyway, what means, that foo() should not know anything about $a, except you give it as a parameter

Upvotes: 0

Related Questions