Почему возникает ошибка
Ошибка undefined variable появляется при попытке обратиться к не существующей (не объявленной ранее) переменной:
<?php
echo $text;
Если в настройках PHP включено отображение ошибок уровня E_NOTICE, то при запуске этого кода в браузер выведется ошибка:
Notice: Undefined variable: text in D:ProgramsOpenServerdomainstest.localindex.php on line 2
Как исправить ошибку
Нужно объявить переменную перед обращением к ней:
$a = '';
echo $a;
Нет уверенности, что переменная будет существовать? Можно указать значение по-умолчанию:
<?php
if(!isset($text))
$text = '';
echo $text;
Или сокращённые варианты:
<?php
// С оператором объединения с null (PHP 7+)
$text = $text ?? '';
// С оператором присваивания значения null (PHP 7.4+)
$text ??= '';
Есть ещё один вариант исправления этой ошибки – отключить отображение ошибок уровня E_NOTICE:
<?php
error_reporting(E_ALL & ~E_NOTICE);
echo $a; // Ошибки не будет
Не рекомендую этот вариант. Скрытие ошибок вместо их исправления – не совсем правильный подход.
Кроме этого, начиная с PHP 8 ошибка undefined variable перестанет относиться к E_NOTICEи так легко отключить её уже не удастся.
Если ошибка появилась при смене хостинга
Часто ошибка возникает при переезде с одного сервера на другой. Практически всегда причина связана с разными настройками отображения ошибок на серверах.
По-умолчанию PHP не отображает ошибки уровня E_Notice, но многие хостинг-провайдеры предпочитают настраивать более строгий контроль ошибок. Т.е. на старом сервере ошибки уже были, но игнорировались сервером, а новый сервер таких вольностей не допускает.
Остались вопросы? Добро пожаловать в комментарии. 🙂
Today, I have started to learn PHP. And, I have created my first PHP file to test different variables. You can see my file as follows.
<?php
$x = 5; // Global scope
function myTest()
{
$y = 10; // Local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
I have found the following errors when I have run this file in the browser.
Notice: Undefined variable: x in /opt/lampp/htdocs/anand/php/index.php on line 19
Notice: Undefined variable: y in /opt/lampp/htdocs/anand/php/index.php on line 29
How can I fix the issue regarding it?
asked Dec 5, 2013 at 4:59
1
The first error ($x
is undefined) is because globals are not imported into functions by default (as opposed to “super globals”, which are).
You need to tell your function you’re referencing the global variable $x
:
function myTest()
{
global $x; // $x refers to the global variable
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
Otherwise, PHP cannot tell whether you are shadowing the global variable with a local variable of the same name.
The second error ($y
is undefined), is because local scope is just that, local. The whole point of it is that $y
doesn’t “leak” out of the function. Of course you cannot access $y
later in your code, outside the function in which it is defined. If you could, it would be no different than a global.
answered Dec 5, 2013 at 5:01
user229044♦user229044
231k40 gold badges328 silver badges336 bronze badges
<?php
$a = 1; /* Global scope */
function test()
{
echo $a; /* Reference to local scope variable */
}
test();
?>
You are getting the first error because the variable $a can’t access the global variable’s value unless you explicitly declare global $a
inside the function.
Example #1 Using a global
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b; // If you want to access a global variable,
// you have to use the 'global' keyword
$b = $a + $b;
}
Sum();
echo $b;
?>
And the last error you are getting because $y is defined inside the function mytest()
so its scope will be limited to that function only.
For a detailed explanation, read Variable scope.
answered Dec 5, 2013 at 5:01
R RR R
3,0032 gold badges24 silver badges42 bronze badges
Set $x as a global, like
global $x;
Or try this:
<?php
$x = 5; // Global scope
function myTest($x)
{
$y=10; // Local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest($x);
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
answered Dec 5, 2013 at 5:03
There are two cases of using a variable globally:
- Using a single copy of that variable and modify it from anywhere i.e. modification from within a function or outside i.e. in the global scope. In that case you need a declaration in the allowed set of function in the form
global $x;
. - In case you need local variables for individual functions with the same identifier used for the global variable (i.e. variables outside all functions); in that case you have two variables with the same name i.e. one local and one global for that function. Then you need to use a superglobal variable
$GLOBALS
i.e. an array of all the global variables. I personally prefer this approach to make efficient code;
The following are the code for the two.
Code 1 (using global declaration)
<?php
$x = 5; // Global scope
function myTest()
{
$y = 10; // Local scope
global $x;
echo "<p>Test variables inside the function:<p>";
echo "Variable x in global scope is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
Code 2 (using the $GLOBALS[] array)
<?php
$x = 5; // Global scope
function myTest()
{
$y = 10; // Local scope
$x = 23;
echo "<p>Test variables inside the function:<p>";
echo "Variable x in global scope is: " . $GLOBALS['x'];
echo "<br>Variable x in local scope is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
For REFERENCE.
answered Dec 5, 2013 at 5:09
Rajesh PaulRajesh Paul
6,7236 gold badges40 silver badges56 bronze badges
The code is behaving as expected, but if you want to use both the variables across the script use this:
<?php
$x = 5; // Global scope
function myTest(){
global $x;
global $y;
$y = 10;
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
answered Dec 5, 2013 at 5:14
In PHP, global variables must be declared global inside a function if they are going to be used in that function.
function myTest()
{
$y = 10; // Local scope
global $x;
.....
}
By declaring $x global within the function, it will refer to the global version of the variable.
answered Dec 5, 2013 at 5:03
LingaLinga
10.3k10 gold badges52 silver badges104 bronze badges
You have to learn the scope of a variable in PHP. See Variable scope.
In your code, $x is a global one, so in order to access that variable inside the function use global $x;
at the beginning of the function, that is,
function myTest()
{
global $x;
$y = 10; // Local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
For $y, either you skip that output by checking isset($y) or else assign a default value at the global scope.
answered Dec 5, 2013 at 5:04
gvgvgvijayangvgvgvijayan
1,83118 silver badges34 bronze badges
put $x outside the”” in code like echo” Variable $x is:”.$x;
answered Sep 4, 2021 at 10:08
John Mwaniki / 10 Dec 2021
This error, as it suggests, occurs when you try to use a variable that has not been defined in PHP.
Example 1
<?php
echo $name;
?>
Output
Notice: Undefined variable: name in /path/to/file/file.php on line 2.
Example 2
<?php
$num1 = 27;
$answer = $num1 + $num2;
echo $answer;
?>
Output
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
isset($variable)
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
<?php
//Example 1
$name = "Raju Rastogi";
if(isset($name)){
$result = "The name is $name";
}
else{
$result = "The name has not been set";
}
echo $result;
//Output: The name is Raju Rastogi
echo "<br>"
//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.
<?php
$name = "Farhan Qureshi";
echo $name;
//Output: Farhan Qureshi
?>
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.
<?php
$num1 = 27;
if(isset($num1) && isset($num2)){
$answer = $num1 + $num2;
echo $answer;
}
?>
The addition operation will not take place because one of the required variables ($num2) has not been set.
<?php
$num1 = 27;
$num2 = 8;
if(isset($num1) && isset($num2)){
$answer = $num1 + $num2;
echo $answer;
}
//Oputput: 35
?>
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
<?php
$name = "John Doe";
$name = isset($name) ? $name : '';
$age= isset($age) ? $age: 0;
echo "My name is $name and I am $age yrs old.";
//Output: My name is John Doe and I am 0 yrs old.
?>
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
Replace it with:
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.
Notice: Undefined variable
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:
<?php
$name='Stechies';
echo $name;
echo $age;
?>
Output:
STechies
Notice: Undefined variable: age in testsite.locvaraible.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.
- Resolve such notices.
- Ignore 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:
<?php
global $name;
global $age;
$name = 'Stechies';
if(!isset($name)){
$name = 'Variable name is not set';
}
if(!isset($age)){
$age = 'Varaible age is not set';
}
echo 'Name: ' . $name.'<br>';
echo 'Age: ' . $age;
?>
Set Index as blank
<?php
$name = 'Stechies';
// Set Variable as Blank
$name = isset($name) ? $name : '';
$age= isset($age) ? $age: '';
echo 'Name: ' . $name.'<br>';
echo 'Age: ' . $age;
?>
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:
error_reporting = E_ALL
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.
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
Now your PHP compiler will show all errors except ‘Notice.’
В логах получаю ошибку PHP Notice: Undefined variable: col in
вот код:
<div class="col-sm-<?php echo $col; ?>">
Как это исправить? Понял, что отвечает за шаблон.
-
Вопрос заданболее года назад
-
209 просмотров
$col не инициализирована!
Где-то ранее в вашем коде, когда вы её только объявляете,
напишите значение по умолчанию. Например $col = 12;
И нет надобности выводить через echo, есть более короткая запись для таких случаев:
<?php=$col;?>
или (если поддерживается short_open_tags
<?=$col;?>
Undefined variable в переводе с английского означает, что такой переменной нет.
Это значит что ошибка в логике, попытка вывести переменную, которой не было присвоено никакое значение.
Соответственно, эту логическую ошибку надо исправить – либо присвоить какое-то значение, либо не выводить.
Пригласить эксперта
-
Показать ещё
Загружается…
20 мая 2023, в 14:47
5000 руб./за проект
20 мая 2023, в 14:41
2000 руб./за проект
20 мая 2023, в 14:16
300000 руб./за проект