Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * This class assumes it is in some kind of framework.
- * It has 'data' passed in, then the $this->var function will get data either in the $this->data object if $name is string
- * or it will return from an object passed in.
- * It converts the object into an array and keeps a copy in cache for later use so the json_encode and json_decode is not called
- * multiple times.
- */
- class View {
- public __construct($data = null){
- $this->cache = [];
- $this->data = $data
- }
- public function var($name, $var, $default = '', $defaultOnEmpty = false){
- if(is_string($name)) {
- $hash = spl_object_hash($this->{$name});
- $object = $this->{$name};
- } else {
- $hash = spl_object_hash($name);
- $object = $name;
- }
- if(!isset($this->cache[$hash])) $this->cache[$hash] = json_decode(json_encode($object), true);
- $object = $this->cache[$hash];
- $token = strtok($var, '.');
- while ($token !== false) {
- if (!isset($object[$token])) return $default;
- $object = $object[$token];
- $token = strtok('.');
- }
- if($defaultOnEmpty && empty($object)) return $default;
- return $object;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement