PHP: Detecting when a variables value has been changed

微笑、不失礼 提交于 2019-12-05 06:10:24

If you want to implement own event handlers / triggers in array or anything else, then you might use class wrapper.

For one variable __get() and __set() magic methods are enough, as you noticed. For array there is a better handler: ArrayAccess. It allows to emulate array actions with class methods and common array semantics (like collections in some other languages).

<?php
header('Content-Type: text/plain');

// ArrayAccess for Array events
class TriggerableArray implements ArrayAccess {
    protected $array;      // container for elements
    protected $triggers;   // callables to actions

    public function __construct(){
        $this->array    = array();

        // predefined actions, which are availible for this class:
        $this->triggers = array(
            'get'    => null,     // when get element value
            'set'    => null,     // when set existing element's value
            'add'    => null,     // when add new element
            'exists' => null,     // when check element with isset()
            'unset'  => null      // when remove element with unset()
        );
    }

    public function __destruct(){
        unset($this->array, $this->triggers);
    }

    public function offsetGet($offset){
        $result = isset($this->array[$offset]) ? $this->array[$offset] : null;

        // fire "get" trigger
        $this->trigger('get', $offset, $result);

        return $result;
    }

    public function offsetSet($offset, $value){
        // if no offset provided
        if(is_null($offset)){
            // fire "add" trigger
            $this->trigger('add', $offset, $value);

            // add element
            $this->array[] = $value;
        } else {
            // if offset exists, then it is changing, else it is new offset
            $trigger = isset($this->array[$offset]) ? 'set' : 'add';

            // fire trigger ("set" or "add")
            $this->trigger($trigger, $offset, $value);

            // add or change element
            $this->array[$offset] = $value;
        }
    }

    public function offsetExists($offset){
        // fire "exists" trigger
        $this->trigger('exists', $offset);

        // return value
        return isset($this->array[$offset]);
    }

    public function offsetUnset($offset){
        // fire "unset" trigger
        $this->trigger('unset', $offset);

        // unset element
        unset($this->array[$offset]);
    }

    public function addTrigger($trigger, $handler){
        // if action is not availible and not proper handler provided then quit
        if(!(array_key_exists($trigger, $this->triggers) && is_callable($handler)))return false;

        // assign new trigger
        $this->triggers[$trigger] = $handler;

        return true;
    }

    public function removeTrigger($trigger){
        // if wrong trigger name provided then quit
        if(!array_key_exists($trigger, $this->triggers))return false;

        // remove trigger
        $this->triggers[$trigger] = null;

        return true;
    }

    // call trigger method:
    // first arg  - trigger name
    // other args - trigger arguments
    protected function trigger(){
        // if no args supplied then quit
        if(!func_num_args())return false;

        // here is supplied args
        $arguments  = func_get_args();

        // extract trigger name
        $trigger    = array_shift($arguments);

        // if trigger handler was assigned then fire it or quit
        return is_callable($this->triggers[$trigger]) ? call_user_func_array($this->triggers[$trigger], $arguments) : false;
    }
}

function check_trigger(){
    print_r(func_get_args());
    print_r(PHP_EOL);
}

function check_add(){
    print_r('"add" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_get(){
    print_r('"get" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_set(){
    print_r('"set" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_exists(){
    print_r('"exists" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_unset(){
    print_r('"unset" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

$victim = new TriggerableArray();

$victim->addTrigger('get', 'check_get');
$victim->addTrigger('set', 'check_set');
$victim->addTrigger('add', 'check_add');
$victim->addTrigger('exists', 'check_exists');
$victim->addTrigger('unset', 'check_unset');

$victim['check'] = 'a';
$victim['check'] = 'b';

$result = $victim['check'];

isset($victim['check']);
unset($victim['check']);

var_dump($result);
?>

Shows:

"add" trigger
Array
(
    [0] => check
    [1] => a
)

"set" trigger
Array
(
    [0] => check
    [1] => b
)

"get" trigger
Array
(
    [0] => check
    [1] => b
)

"exists" trigger
Array
(
    [0] => check
)

"unset" trigger
Array
(
    [0] => check
)

string(1) "b"

I assume, that you might modify constructor in this code with array reference argument to be able to pass there superglobal array, like $_COOKIE. Another way is to replace $this->array with $_COOKIE directly within class. Also, there is a way to replace callables with anonymous functions.

How about never changing the variable at all.

How about only accessing the variable through a function (or class method) that can handle whatever "listening" tasks you wanted to perform?

Why must you do: $variable = 5; ?

When you could do: setMyVariable(5) ?

function setMyVariable($new_value) {
  $variable = $new_value;
  // do other stuff

}

I think you have some error in your thinking because they only way a variable can change its value in php is if you change it. Therefore, when you change your variable, run your code.

If you need a generic way of doing this, I would suggest encapsulating either the array or its values into a class. But there really is no good reason you can't just run sendCookie() after each value change.

Change listeners are for multi-threaded programming I think.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!