note 116576 added to jsonserializable.jsonserialize
| From: | Anonymous | Date: | Fri, 23 Jan 2015 18:34:52 +0000 |
| Subject: | note 116576 added to jsonserializable.jsonserialize | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-201512@lists.php.net to get a copy of this message | ||
Serialize private attributes to JSON in PHP 5.3
<?php
abstract class Model {
public function jsonSerialize() {
$getter_names = get_class_methods(get_class($this));
$gettable_attributes = array();
foreach ($getter_names as $key => $value) {
if(substr($value, 0, 4) === 'get_') {
$gettable_attributes[substr($value, 4, strlen($value))] = $this->$value();
}
}
return $gettable_attributes;
}
}
class Content extends Model {
private $title;
private $text;
public function get_title() {
return $this->title;
}
public function set_title($title) {
$this->title = $title;
}
public function get_text() {
return $this->text;
}
public function set_text($text) {
$this->text = $text;
}
}
$content = new Content();
$content->set_title('lol');
$content->set_text('haha');
echo json_encode($content->jsonSerialize());
?>
----
Server IP: 72.52.91.14
Probable Submitter: 178.84.245.68
----
Manual Page -- http://php.net/manual/en/jsonserializable.jsonserialize.php
Edit -- https://master.php.net/note/edit/116576
Del: integrated -- https://master.php.net/note/delete/116576/integrated
Del: useless -- https://master.php.net/note/delete/116576/useless
Del: bad code -- https://master.php.net/note/delete/116576/bad+code
Del: spam -- https://master.php.net/note/delete/116576/spam
Del: non-english -- https://master.php.net/note/delete/116576/non-english
Del: in docs -- https://master.php.net/note/delete/116576/in+docs
Del: other reasons-- https://master.php.net/note/delete/116576
Reject -- https://master.php.net/note/reject/116576
Search -- https://master.php.net/manage/user-notes.php