Last active
December 30, 2017 16:42
-
-
Save trafficinc/790c55cbeb8e2174832121185db13665 to your computer and use it in GitHub Desktop.
Create JS like object in PHP for quick object creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Creating a JS 'like' Object in PHP | |
class JSObject { | |
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); | |
} | |
} | |
} | |
// Object | |
$person = new JSObject([ | |
'name' => "Adentu", | |
'age'=> 37, | |
'say' => "Hello World" | |
]); | |
echo $person->name; | |
echo "\r\n"; | |
echo $person->age; | |
echo "\r\n"; | |
echo $person->say; | |
/* | |
Adentu | |
37 | |
Hello World | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment