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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

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

Post 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?
Last edited by Jonah Bron on Tue Aug 17, 2010 1:09 pm, edited 1 time in total.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Is Using @$_REQUEST A Good Idea?

Post 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');

Gargoyle
Forum Contributor
Posts: 130
Joined: Wed Jul 14, 2010 12:25 am

Re: Is Using @$_REQUEST A Good Idea?

Post 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'] : '';
Post Reply