PHP 에러중에 "Undefined variable" 나타날때, 해당 값의 변수의 초기값이 없을때, 나타난다.
해당 방법을 없애는 것은 경고 메시지를 보이지 않게 하던지. 해당 변수값의 초기값을 주면 해결된다.
또는 내가 무심결에 소스에 Error보기 설정이 되어 있을때도 에러나 날수 있습니다.
// we will do our own error handling |
참고로 저의 경우 retune $tmp; 을 넘길때, $tmp값을 선언하지 않았을때, 에러가 났다.
$tmp가 array타입이라서 $tmp = []; 로 선언해 줬습니다.
아래는 에러에 대한 설명들이 잘 나와 있어서 배껴둡니다.
Notice: Undefined variable
From the vast wisdom of the PHP Manual:
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset()language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.
From PHP documentation:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
This means that you could use only empty()
to determine if the variable is set, and in addition it checks the variable against the following, 0,"",null
.
Example:
$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
echo (!isset($v) || $v == false) ? 'true ' : 'false';
echo ' ' . (empty($v) ? 'true' : 'false');
echo "\n";
});
Test the above snippet in the 3v4l.org online PHP editor
Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE
, one that is not even reported by default, but the Manual advises to allow during development.
Ways to deal with the issue:
-
Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use
isset()
/!empty()
to check if they are declared before referencing them, as in://Initializing variable $value = ""; //Initialization value; Examples //"" When you want to append stuff later //0 When you want to add numbers later //isset() $value = isset($_POST['value']) ? $_POST['value'] : ''; //empty() $value = !empty($_POST['value']) ? $_POST['value'] : '';
This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:
// Null coalesce operator - No need to explicitly initialize the variable. $value = $_POST['value'] ?? '';
-
Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):
set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
-
Disable E_NOTICE from reporting. A quick way to exclude just
E_NOTICE
is:error_reporting( error_reporting() & ~E_NOTICE )
-
Suppress the error with the @ operator.
Note: It's strongly recommended to implement just point 1.
Notice: Undefined index / Undefined offset
This notice appears when you (or PHP) try to access an undefined index of an array.
Ways to deal with the issue:
-
Check if the index exists before you access it. For this you can use
isset()
orarray_key_exists()
://isset() $value = isset($array['my_index']) ? $array['my_index'] : ''; //array_key_exists() $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
-
The language construct
list()
may generate this when it attempts to access an array index that does not exist:list($a, $b) = array(0 => 'a'); //or list($one, $two) = explode(',', 'test string');
Two variables are used to access two array elements, however there is only one array element, index 0
, so this will generate:
Notice: Undefined offset: 1
$_POST
/ $_GET
/ $_SESSION
variable
The notices above appear often when working with $_POST
, $_GET
or $_SESSION
. For $_POST
and $_GET
you just have to check if the index exists or not before you use them. For $_SESSION
you have to make sure you have the session started with session_start()
and that the index also exists.
Also note that all 3 variables are superglobals. This means they need to be written in uppercase.
Related:
'WEB언어 > PHP' 카테고리의 다른 글
gmail 계정으로 이메일 보내기 + AWS에서 PHP를 이용한 SMTP를 통해 이메일 전송 (0) | 2017.12.16 |
---|---|
[PHP] 접속자 IP 알아내기 함수. (0) | 2017.12.12 |
PHP 객체지향 방식 (0) | 2017.11.30 |
[PHP] HTTP와 HTTPS에 따라 URL변경하기 (0) | 2017.10.26 |
(따옴표) Single쿼텐션 없애기 / 엔터 없애기 / GET방식 & 와 + 전송하기 (0) | 2017.10.13 |
PHP mysql_real_escape_string사용하지 않는 방법 (0) | 2017.10.13 |
[PHP] addslashes(), stripslashes() 그리고, get_magic_quotes_gpc() (0) | 2017.07.19 |
날짜 포멧 yyyy-dd-mm을 dd/mm/yyyy 변환 (0) | 2017.06.24 |
(로그인하지 않으셔도 가능)