Page 1 of 1

[SOLVED] Is Using @$_REQUEST A Good Idea?

Posted: Mon Aug 16, 2010 12:43 pm
by Jonah Bron
Hello, world!

Having a chunk of code that looks like this to check every post/get field is annoying.

Code: Select all

if (isset($_POST['somefield'])) {
    $somefield = $_POST['somefield'];
} else {
    $somefield = '';
}

// or maybe this

$somefield = isset($_POST['somefield']) ? $_POST['somefield'] : '';

// or maybe this

function _POST($field) {
    return isset($_POST[$field]) ? $_POST[$field] : '';
}

$somefield = _POST('somefield');
All that code just to depress an Undefined Index Notice. I know @$_POST['somefield'] works, but is it a good idea? What is the best way to do this?

Re: Is Using @$_REQUEST A Good Idea?

Posted: Mon Aug 16, 2010 1:34 pm
by John Cartwright
Anything that internally triggers an E_NOTICE is enough grounds, in my opinion, to consider it a bad practice. There are however several ways to deal with this,

The ternary operator:

Code: Select all

$somefield = isset($_POST['somefield']) ? $_POST['somefield'] : '';
A data container object:

Code: Select all

class DataContainer 
{
   protected $_source = array();

   public function __construct(array $source) 
   {
      $this->_source = $source;
   } 

   public function __get($name) 
   {
      return $this->get($name);
   }

   public function get($name) 
   {
      if (array_key_exists($name, $this->_source)) {
         if (is_array($this->_source[$name])) {
            return new DataContainer($this->_source[$name]);
         }
         return $this->_source[$name];
      }
      return null;
   }   

   public function toArray() 
   {
      return $this->_source;
   }
}

$data = new DataContainer($_POST);
echo $data->foobar; //will either return null or value, no notices
//echo $data->get('foobar');

//you can also step through multiple array levels fluently, i.e.,
echo $data->foobar->feebar;
//echo $data->get('foobar')->get('feebar');


Re: Is Using @$_REQUEST A Good Idea?

Posted: Mon Aug 16, 2010 2:01 pm
by Gargoyle
Anything that internally triggers an E_NOTICE is enough grounds, in my opinion, to consider it a bad practice.
+1

I prefer this:

Code: Select all

$somefield = isset($_POST['somefield']) ? $_POST['somefield'] : '';