Laravel request class mockup on accessing data
$request->name // works $request['name'] // worksunknown
php
3 years ago
3.0 kB
4
Indexable
<?php class Request implements ArrayAccess { private $attributes = [ 'name' => 'Zihad', 'position' => 'Software Engineer', 'expected_salary' => '2,50,500' ]; /* * Returns value from the Attribute property * @param string $name * @return mixed */ public function __get($name) { return $this->get($name); } /* * Get values associated to the keys * @param array|string|null $arguments * @return mixed */ public function get($arguments = null) { // If no keys are specified then returns whole attributes array if (!$arguments) { return $this->attributes; } // If specified multiple keys in array then return associated key => values if (is_array($arguments)) { return $this->getAttributes($arguments); } // If specified key is available in the attribute property then returns the value if (isset($this->attributes[$arguments])) { return $this->attributes[$arguments]; } // If nothing found then return null return null; } /* * Returns values binded to the keys * @param array $keys * @return array */ private function getAttributes($keys) { $temp = []; foreach($keys as $key) { if (isset($this->attributes[$key])) { $temp[$key] = $this->attributes[$key]; } else { $temp[$key] = null; } } return $temp; } /* * Check if the key exists in attributes * @param string $key * @return boolean */ public function offsetExists($key) { return isset($this->attributes[$key]); } /* * Returns attributes value related to key * @param string $key * @return mixed */ public function offsetGet($key) { return $this->get($key); } /* * Set new value to attributes * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value) { $this->attributes[$key] = $value; } /* * Unset value in attributes * @param mixed $key * @return void */ public function offsetUnset($key) { $this->attributes[$key] = null; } } $request = new Request; echo $request->name; // Prints : Zihad echo $request['position']; // Prints : Software Engineer echo $request->attributes->name; // Will not work // SUCCESS ================================ ?>
Editor is loading...