Skip to content
Advertisement

how to hide properties of class during serialization?

can i override function that is responsbile for serializing and Php class to an array/stdclass so that i can implement my own logic “like hiding certain attributes based on condition)

class UserModel{
  $hidden = ['password'];

  function __construct(array $data) {
    foreach($data as $key=>$value)$this->$key = $value;
  }

}

$user = new UserModel(['id'=>1,'password'=>123]);

var_dump($user);

Advertisement

Answer

How about implementing the Serializable interface? Looks like you can do your custom logic by implementing the interface methods.

Example:

class UserModel implements Serializable {

    // returns string
    public function serialize() {
        $data = array(
            'id' => $this->id,
            'password' => null, // or omit password
            'email' => $this->email,
            ...
        );
        return serialize($data);
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement