I would like to know the correct method to define & check for variables, arrays & variable variables to avoid error reporting Notice being thrown.
Over the years I've developed a few bad coding habits & I discovered many old scripts are throwing Notice warnings for undefined vars.
Most of them I can easily fix by first declaring the $var as an empty string or 0 or array()
Code: Select all
$var="";
if($var=="greeting"){
echo "hello";
}Code: Select all
if(!empty($_POST['var']) && $_POST['var']=="test"){
echo "this is a test";
}Also, while working on this, I found a behaviour which seemed odd.
I found an old page which is used for creating products in a database & it was throwing several Notice errors. The page is used for both NEW products & EDITING existing products.
In the case of the product ID being passed in, it would get product data in the array $line, if no ID is passed in it must be a new product and so $line doesnt exist.
Code: Select all
<th>Product Name</th>
<td><input name="ProductName" type="text" value="<?php echo $line['ProductName']; ?>" /></td>Code: Select all
global $line;I have never used "global" in this way before, I would normally only use it inside a function to reference external $vars.
Is this a valid use? Why is it suppressing all Notices? If I declare like this instead...
Code: Select all
$line=array();Hope this isnt too long winded, just want to correctly understand & handle vars like this. I should know better.
Note: I realise I can suppress the Notice warnings, but this exercise is to eliminate them completely.