Last active
April 20, 2021 12:28
-
-
Save makomweb/fab43f3654623529d24382a858e50f65 to your computer and use it in GitHub Desktop.
PHP equivalent to C# dynamic
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 | |
class dynamic { | |
private $data; | |
public function __construct($data) { | |
$this->data = $data; | |
} | |
public function __call($method, $arguments) { | |
if (true === array_key_exists($method, $this->data)) { | |
if (0 < is_array($this->data[$method]) && count($arguments)) { | |
if (true === array_key_exists($arguments[0], $this->data[$method])) { | |
return new self($this->data[$method][$arguments[0]]); | |
} | |
} | |
return $this->data[$method]; | |
} | |
} | |
} | |
$data = [ | |
'users' => [ | |
1 => [ | |
'name' => 'sample', | |
'age' => 21 | |
], | |
5 => [ | |
'name' => 'sample', | |
'age' => 25, | |
'books' => [ | |
1 => [ | |
'title' => 'Moby Dick' | |
] | |
] | |
] | |
] | |
]; | |
$obj = new dynamic($data); | |
printf('$obj->users(1)->age() = %d' . PHP_EOL, $obj->users(1)->age()); | |
printf('$obj->users(5)->age() = %d'. PHP_EOL, $obj->users(5)->age()); | |
printf('$obj->users(5)->books(1)->title() = %s' . PHP_EOL, $obj->users(5)->books(1)->title()); | |
/* | |
run with php dynamic.php | |
output is: | |
$obj->users(1)->age() = 21 | |
$obj->users(5)->age() = 25 | |
$obj->users(5)->books(1)->title() = Moby Dick | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment