What's the best way to get rid of notices about undefined variables?
I use codeigniter, one of the main issues i have with the views is undefined variables that may or may not exist.
I know that it's easy to get rid of the notices when using something like:
<?=html($this->in开发者_开发知识库put->post('name'))?>
By adding if(isset(..){ html($this->input->post('name')); }
But it's very annoying and it makes the code look ugly, I also don't want to disable notice reporting.
Is there any advice about that?
The "best" way? I still say it's isset
. It's nice to be explicit, and it would help me, as someone maintaining your code later, to realize that you are okay with that variable not existing and that it wasn't just a mistake. Unless the isset
check were there, I'd assume you just didn't realize it was possible for it not to be set, and would wonder what you actually meant to do.
Additionally, I'd assert that one of the main reasons it looks ugly is because all the code is being crammed into one line. There are two things you're trying to do: check if it's set, and print it if so. Maybe spacing them out would look nicer, even if it's a bit more verbose:
<?php if( isset($this->input->post('name')) ): ?>
<?= $this->input->post('name') ?>
<?php endif ?>
This also makes the snippet easier to manage later, in case you later decide to, say, wrap the output in an HTML tag, or add an else
case.
Plus, since, according to the question, we can't mess with the error reporting settings, checking for the variable's existence is the only option. Sorry. Either you check if it's set, or disable the error messages saying it's not. No middle road.
I guess you'll find the error reporting() php function located at the top of your main index.php file. Then have a look to the php manual that says for your question :
error_reporting(E_ALL ^ E_WARNING);
The best way is to define your variables always. If the variable is an input (i.e. You don't know whether it is defined or not) then using isset() required. Personally I use a wrapper function to get data from input variables:
function get($key, $default = null) {
return isset($_GET[$key]) ? $_GET[$key] : $default);
}
Then instead of using $_GET['some_key']
you can use get('some_key')
.
You can also suppress errors using at sign (@) which I do not recommend.
Just put this in your controller in function __construct() part.
function __construct() {
parent::__construct();
error_reporting(E_ALL ^ (E_NOTICE));
}
精彩评论