Laravel Request class clone

Access values of an array which is a property of a class, directly without any middleman
 avatar
unknown
php
3 years ago
2.0 kB
4
Indexable
<?php
  class Request {
      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;
      }
  }

  $request = new Request;
  
  // This syntax is working
  echo $request->name;  // Prints : Zihad

  // This syntax is not working
  echo $request['position'];  // Prints : Software Engineer
?>
Editor is loading...