PHP Syntactic Sugar

Haoran Un
Haoran Un
May 30 · 2 min read

The End

class JsonThing {public function __get($key) {
$this->$key = new JsonThing();
return $this->$key;
}
public function __set($key, $value) {
$this->$key = $value;
}
}class SomeOtherClass extends JsonThing { ... }

The Beginning

{
"item":
{
"id": 511660,
"title": "article title",
"date": {
"modified": "2016-01-16T10:00:00+01:00",
"published": "2016-01-10T10:00:00+01:00"
}
}
}

The Middle

class Document extends JsonThing { ... }// ...$document = new Document();
$document->item->id = 511660;
$document->item->title = 'article title';
$document->item->date->modified = "2016-01-16T10:00:00+01:00";
$document->item->date->published = "2016-01-10T10:00:00+01:00";
return json_encode($document);
class DefaultStyles extends JsonThing {
public $font = 'Georgia';
public $fontSize = 12;
public $colour = '#333';
}
// ...$document->styles = new DefaultStyles();
$document->validate();
return json_encode($document);

Alternate Versions

Ugly version 1

$document = [];
$document['item'] = [];
$document['item']['id'] = 511660;
$document['item']['title'] = 'article title';
$document['item']['date'] = [];
$document['item']['date']['modified'] = "2016-01-10T10:00:00+01:00";
$document['item']['date']['published'] = "2016-01-16T10:00:00+01:00";
return json_encode($document);
$document->addStyles();$document->setDateModified('yesterday');public function setDateModified($date) {
$this->date->published = strtotime($value);
}
}

Ugly Version 2

$document = new Document();$document->item = new Item();
$document->item->id = 511660;
$document->item->title = 'article title';
$document->item->date = new DocumentDate();
$document->item->date->modified = '2016-01-16T10:00:00+01:00';
$document->item->date->published= '2016-01-10T10:00:00+01:00';
return json_encode($document);
Haoran Un

Written by

Haoran Un

Code geek. Board game geek. Coffee geek. Bible geek.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade