Skip to content

Instantly share code, notes, and snippets.

@nyancodeid
Created February 26, 2018 04:52
Show Gist options
  • Save nyancodeid/67c2979caf544a1aef73f3560673fad0 to your computer and use it in GitHub Desktop.
Save nyancodeid/67c2979caf544a1aef73f3560673fad0 to your computer and use it in GitHub Desktop.
JavaScript-style object literals in PHP
<?php
class Objects {
function __construct($members = array()) {
foreach ($members as $name => $value) {
$this->$name = $value;
}
}
function __call($name, $args) {
if (is_callable($this->$name)) {
array_unshift($args, $this);
return call_user_func_array($this->$name, $args);
}
}
}
$me = new Objects(array(
'name' => "Ryan",
'isValid'=> true,
'say' => function($user) {
if ($user->isValid) {
return "Hi, " . $user->name;
}
}
));
echo $me->say(); // Hi, Ryan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment