Last active
May 16, 2018 12:42
-
-
Save wilcorrea/e90bcb229ff68ce8eb2c86997ac79620 to your computer and use it in GitHub Desktop.
Create a object from associative array
This file contains 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 | |
$value = new Value(['name' => 'William']); | |
echo $value; |
This file contains 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 | |
namespace App; | |
/** | |
* Class Value | |
*/ | |
class Value | |
{ | |
/** | |
* @var | |
*/ | |
private $attributes; | |
/** | |
* Value constructor. | |
* @param $attributes | |
*/ | |
public function __construct($attributes = []) | |
{ | |
$this->attributes = $attributes; | |
} | |
/** | |
* @param $key | |
* @param $value | |
*/ | |
public function __set($key, $value) | |
{ | |
$this->attributes[$key] = $value; | |
} | |
/** | |
* @param $key | |
* @return null | |
*/ | |
public function __get($key) | |
{ | |
return isset($this->attributes[$key]) ? $this->attributes[$key] : null; | |
} | |
/** | |
* @return string | |
*/ | |
public function __debugInfo() | |
{ | |
return $this->__toString(); | |
} | |
/** | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return json_encode($this->attributes); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment