Hide specific class fields from print_r or var_dump

前端 未结 6 1631
无人及你
无人及你 2021-01-02 01:22

Is it possible to hide a specific class fields from print_r ?



        
6条回答
  •  我在风中等你
    2021-01-02 01:28

    You can use simple closure to hide the sensitive data.

    class PrivateValue {
        private $val;
        public function __construct($val) {
            $this->val = function() use ($val) { return $val; };
        }
        public function getValue() {
            return ($this->val)();
        }
        public fucntion __debugInfo() {
             return [ 'val' => '***' ]; // TODO
        }
    }
    

    Storing the closure rather than value hides the value from everything I can think of. The getter then retrieves the value by invoking the closure. The __debugInfo method provides some useful but safe representation for developers as var_dump will show it. Unhandled features like var_export will show 'closure', but not the boud value.

    Keep in mind that some tools my try too hard and dig out these data too.

    I've got the inspiration from other answers here. — Thank you!

提交回复
热议问题