«Notice: Undefined variable» в PHP
Многие начинающие разработчики PHP видят на экране или в логах сообщения типа “Notice: Undefined variable”, означающее, что была использована переменная, которая не объявлена заранее. Дело в том, что PHP является очень гибким языком программирования, позволяя использовать переменные без инициализации.
В этом нет ничего плохого, но если вы хотите писать по-настоящему чистый код, вам следует отлавливать и исключать любые предупреждения компилятора. Предупреждение типа Notice практически никак не влияют на работу программы, просто они говорят разработчику, на что он должен обратить внимание.
Если разработчик не инициализирует переменные, а начинает их использование с проверки их значения, то при соответствующем уровне вывода ошибок, будет отображено сообщение «Notice: Undefined variable». Инициализация переменных означает присвоение им определенного типа и значения перед использованием. Если этого не сделать, интерпретатор сделает это по своим внутренним правилам, которые могут идти вразрез с пониманием программиста. Кроме того, вы могли выше по коду использовать переменную с тем же именем, не очистив у нее значение. Забыв про такую переменную и не сделав инициализацию, вы гарантированно получите неверные результаты.
Можно выделить 2 метода «борьбы» с описываемыми Notice: выключить предупреждения данного уровня в настройках, или инициализировать указанные переменные. Советую использовать второй путь.
Для тех, кто все же выбрал выключить предупреждения, чтобы они не отображались на экране и в логах, делается это в настройках PHP.INI. Отредактируйте в текстовом редакторе свой файл настроек PHP.INI, отыскав слово error_reporting и внеся такую строку:
error_reporting = E_ALL & ~E_NOTICE
При этом будут отображаться все ошибки, кроме типа E_NOTICE. Подробнее о директиве error_reporting вы можете почитать в самом же файле PHP.INI, там есть обширная справка о директиве error_reporting чуть выше самой директивы.
Буду рад ответить на любые вопросы относительно данной темы и в общем по PHP.
[Solved]: Notice: Undefined variable in PHP
This error, as it suggests, occurs when you try to use a variable that has not been defined in PHP.
Example 1
Notice: Undefined variable: name in /path/to/file/file.php on line 2.
Example 2
Notice: Undefined variable: num2 in /path/to/file/file.php on line 3.
In our above two examples, we have used a total of 4 variables which include $name , $num1 , $num2 , and $answer .
But out of all, only two ($name and $num2) have resulted in the «undefined variable» error. This is because we are trying to use them before defining them (ie. assigning values to them).
In example 1, we are trying to print/display the value of the variable $name, but we had not yet assigned any value to it.
In example 2, we are trying to add the value of $num1 to the value of $num2 and assign their sum to $answer. However, we have not set any value for $num2.
To check whether a variable has been set (ie. assigned a value), we use the in-built isset() PHP function.
Syntax
We pass the variable name as the only argument to the function, where it returns true if the variable has been set, or false if the variable has not been set.
Example
else < $result = "The name has not been set"; >echo $result; //Output: The name is Raju Rastogi echo "
" //Example 2 if(isset($profession)) < $result = "My profession is $profession"; >else < $result = "The profession has not been set"; >echo $result; //Output: The profession has not been set ?>
In our first example above, we have defined a variable ($name) by creating it and assigning it a value (Raju Rastogi) and thus the isset() function returns true.
In our second example, we had not defined our variable ($profession) before passing to the isset() function and thus the response is false.
The Fix for Undefined variable error
Here are some ways in which you can get rid of this error in your PHP program.
1. Define your variables before using them
Since the error originates from using a variable that you have not defined (assigned a value to), the best solution is to assign a value to the variable before using it anywhere in your program.
For instance, in our first example, the solution is to assign a value to the variable $name before printing it.
The above code works without any error.
2. Validating variables with isset() function
Another way to go about this is to validate whether the variables have been set before using them.
The addition operation will not take place because one of the required variables ($num2) has not been set.
The addition this time will take place because the two variables required have been set.
3. Setting the undefined variable to a default value
You can also check whether the variables have been defined using the isset() function and if not, assign them a default value.
For instance, you can set a blank «» value for variables expected to hold a string value, and a 0 for those values expect to hold a numeric value.
Example
4. Disabling Notice error reporting
This is always a good practice to hide errors from the website visitor. In case these errors are visible on the website to the web viewers, then this solution will be very useful in hiding these errors.
This option does not prevent the error from happening, it just hides it.
Open the php.ini file in a text editor, and find the line below:
error_reporting = E_ALL & ~E_NOTICE
Now the ‘NOTICE’ type of errors won’t be shown again. However, the other types of errors will be shown.
Another way of disabling these errors is to add the line of code below on the top of your PHP code.
error_reporting (E_ALL ^ E_NOTICE);
That’s all for this article. It’s my hope that it has helped you solve the error.
Related Articles
How to Fix Notice: Undefined Variable in PHP
PHP is a powerful programming language used by many websites around the world. However, sometimes PHP may throw an error message saying “Notice: Undefined Variable” on your website. This can confuse your website visitors and spoil their user experience. In this article, we will look at what this error message means and how to fix this error message.
How to Fix Notice: Undefined Variable in PHP
When you get an error message “Notice: Undefined Variable” in PHP it means that you are trying to use a variable or constant that is not defined.
Here is an example of this error
In the above example, we have defined $dob variable but are calling $age variable which is not defined. So you will see the following error.
Notice: Undefined variable: age in \test.php on line 3
There are two ways to fix this error. Either you can resolve this error or ignore this error.
Fix Error using isset() function
You can use define your variables as global and use isset() function to test if the variable is set or not before calling it. Here is an example
echo 'Age: ' . $age; ?> Output Variable age is not set
Fix Error by setting variable as blank or default value
Another way to fix this problem, is to set it as blank.
We can also ignore this notice instead of fixing it, though it is not advisable to do so. Here are a couple of ways to disable this error message from appearing.
Disable Display Notice in php.ini file
Open php.ini file in a text editor. Look for the following line
error_reporting = E_ALL & ~E_NOTICE
Restart Apache server to apply changes. Now PHP compiler will show all errors except ‘NOTICE’ type of errors.
Disable displaying Notice in PHP code
If you don’t have access to php.ini file, then just add the following line at the top of your php file to disable notice errors.
That’s it. In this article, we have learnt how to deal with “Undefined Variable” error in PHP. Using variables without defining their values causes this error, and can be easily avoided by using isset() function to check if they are set or not, before using them.
Notice: Undefined Variable in PHP
This error means that within your code, there is a variable or constant which is not set. But you may be trying to use that variable.
The error can be avoided by using the isset() function.This function will check whether the variable is set or not.
Error Example:
Output:
STechies Notice: Undefined variable: age in \testsite.loc\varaible.php on line 4
In the above example, we are displaying value stored in the ‘name’ and ‘age’ variable, but we didn’t set the ‘age’ variable.
Here are two ways to deal with such notices.
Fix Notice: Undefined Variable by using isset() Function
This notice occurs when you use any variable in your PHP code, which is not set.
Solutions:
To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.
Example:
if(!isset($age)) < $age = 'Varaible age is not set'; >echo 'Name: ' . $name.'
'; echo 'Age: ' . $age; ?>
Set Index as blank
Ignore PHP Notice: Undefined variable
You can ignore this notice by disabling reporting of notice with option error_reporting.
1. Disable Display Notice in php.ini file
Open php.ini file in your favorite editor and search for text “error_reporting” the default value is E_ALL. You can change it to E_ALL & ~E_NOTICE.
By default:
Change it to:
error_reporting = E_ALL & ~E_NOTICE
Now your PHP compiler will show all errors except ‘Notice.’
2. Disable Display Notice in PHP Code
If you don’t have access to make changes in the php.ini file, In this case, you need to disable the notice by adding the following code on the top of your PHP page.
Now your PHP compiler will show all errors except ‘Notice.’
- Learn PHP Language
- PHP Interview Questions and Answers
- PHP Training Tutorials for Beginners
- Display Pdf/Word Document in Browser Using PHP
- Call PHP Function from JavaScript
- Call a JavaScript Function from PHP
- PHP Pagination
- Alert Box in PHP
- Php Count Function
- PHP Filter_var ()
- PHP array_push Function
- strpos in PHP
- PHP in_array Function
- PHP strtotime() function
- PHP array_merge() Function
- explode() in PHP
- implode() in PHP
- PHP array_map()