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!
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,
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');