Reputation: 9007
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);
Upvotes: 0
Views: 2314
Reputation: 639
For a simple solution you can also use __sleep Magic Method.
https://www.php.net/manual/en/language.oop5.magic.php
class UserModel {
protected $id;
protected $password;
protected $username;
protected $email;
public function __sleep(){
return array('id','username','email');
}
}
Upvotes: 0
Reputation: 65
You can overwrite a method
Just look at the small exemple of the classe below;
class User {
//To hide
private $pass;
//To show
private $log;
private $nbPoints;
{...}
public function serialize()
{
$arr = [];
$arr['LOG'] = $this->log;
$arr['POINTS'] = $this->nbPoints;
return ($arr);
}
}
You can var_dump the return of the User->serialize
method and password will ne be showed.
If you need all your class, then crypt or hash all variable you need to hide.
Here is two famous (but unsafe) method in cryptology : MD5
Ceaser cipher
Just understand well the difference between hashing and crypting datas
(HASH : https://en.wikipedia.org/wiki/MD5);
(CRYPTING : https://en.wikipedia.org/wiki/Caesar_cipher);
Upvotes: 0
Reputation: 1722
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);
}
}
Upvotes: 1