проверка на undefined php
defined
(PHP 4, PHP 5, PHP 7, PHP 8)
defined — Проверяет существование указанной именованной константы
Описание
Проверяет существование и наличие значения указанной константы.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Проверка констант
Смотрите также
User Contributed Notes 16 notes
// Checking the existence of a class constant, if the class is referenced by a variable.
class Class_A
<
const CONST_A = ‘value A’;
>
// When class name is known.
if ( defined( ‘Class_A::CONST_A’ ) )
echo ‘Class_A::CONST_A defined’;
// Using a class name variable. Note the double quotes.
$class_name = Class_A::class;
if ( defined( «$class_name::CONST_A» ) )
echo ‘$class_name::CONST_A defined’;
final class class2 extends class1
<
const SOME_CONST = 2 ;
>
$class2 = new class2 ;
if you want to check id a class constant is defined use self:: before the constant name:
Before using defined() have a look at the following benchmarks:
true 0.65ms
$true 0.69ms (1)
$config[‘true’] 0.87ms
TRUE_CONST 1.28ms (2)
true 0.65ms
defined(‘TRUE_CONST’) 2.06ms (3)
defined(‘UNDEF_CONST’) 12.34ms (4)
isset($config[‘def_key’]) 0.91ms (5)
isset($config[‘undef_key’]) 0.79ms
isset($empty_hash[$good_key]) 0.78ms
isset($small_hash[$good_key]) 0.86ms
isset($big_hash[$good_key]) 0.89ms
isset($small_hash[$bad_key]) 0.78ms
isset($big_hash[$bad_key]) 0.80ms
PHP Version 5.2.6, Apache 2.0, Windows XP
Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn’t going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):
May want to avoid if(defined(‘DEBUG’)).
I saw that PHP doesn’t have an enum function so I created my own. It’s not necessary, but can come in handy from time to time.
This function, along with constant(), is namespace sensitive. And it might help if you imagine them always running under the «root namespace»:
Dont forget to put the name of your constant into single quotation mark. You will not get an error or a warning.
//output: 12
?>
It took me half an day to see it.
In PHP5, you can actually use defined() to see if an object constant has been defined, like so:
class Generic
<
const WhatAmI = ‘Generic’ ;
>
if ( defined ( ‘Generic::WhatAmI’ ))
<
echo Generic :: WhatAmI ;
>
?>
Thought it may be useful to note.
Check if a variable is undefined in PHP
Consider this JavaScript statement:
I would like to know if we have a similar statement in PHP, not being isset(), but literally checking for an undefined value. Something like:
Is there something similar as the above in PHP?
8 Answers 8
Note: It returns TRUE if the variable exists and has a value other than NULL, FALSE otherwise.
Another way is simply:
You can do it like this:
You’ll not have any error, because the first condition isn’t accepted.
To check if a variable is set you need to use the isset function.
This code will print:
The isset() function does not check if a variable is defined.
It seems you’ve specifically stated that you’re not looking for isset() in the question. I don’t know why there are so many answers stating that isset() is the way to go, or why the accepted answer states that as well.
It’s important to realize in programming that null is something. I don’t know why it was decided that isset() would return false if the value is null.
In the following example it will work the same way as JavaScript’s undefined check.
But in this example, it won’t work like JavaScript’s undefined check.
$variable is being defined as null, but the isset() call still fails.
So how do you actually check if a variable is defined? You check the defined variables.
However, if you’re finding that in your code you have to check for whether a variable has been defined or not, then you’re likely doing something wrong. This is my personal belief as to why the core PHP developers left isset() to return false when something is null.
isset
(PHP 4, PHP 5, PHP 7, PHP 8)
isset — Определяет, была ли установлена переменная значением, отличным от null
Описание
Определяет, была ли установлена переменная значением отличным от null
Если были переданы несколько параметров, то isset() вернёт true только в том случае, если все параметры определены. Проверка происходит слева направо и заканчивается, как только будет встречена неопределённая переменная.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования isset()
// В следующем примере мы используем var_dump для вывода
// значения, возвращаемого isset().
$a = «test» ;
$b = «anothertest» ;
Функция также работает с элементами массивов:
Пример #2 isset() и строковые индексы
Результат выполнения данного примера:
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
При использовании isset() на недоступных свойствах объекта, будет вызываться перегруженный метод __isset(), если он существует.
Смотрите также
User Contributed Notes 30 notes
I, too, was dismayed to find that isset($foo) returns false if ($foo == null). Here’s an (awkward) way around it.
Of course, that is very non-intuitive, long, hard-to-understand, and kludgy. Better to design your code so you don’t depend on the difference between an unset variable and a variable with the value null. But «better» only because PHP has made this weird development choice.
In my thinking this was a mistake in the development of PHP. The name («isset») should describe the function and not have the desciption be «is set AND is not null». If it was done properly a programmer could very easily do (isset($var) || is_null($var)) if they wanted to check for this!
The new (as of PHP7) ‘null coalesce operator’ allows shorthand isset. You can use it like so:
You can safely use isset to check properties and subproperties of objects directly. So instead of writing
isset($abc) && isset($abc->def) && isset($abc->def->ghi)
or in a shorter form
you can just write
without raising any errors, warnings or notices.
How to test for a variable actually existing, including being set to null. This will prevent errors when passing to functions.
«empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.»
!empty() mimics the chk() function posted before.
in PHP5, if you have
I tried the example posted previously by Slawek:
$foo = ‘a little string’;
echo isset($foo)?’yes ‘:’no ‘, isset($foo[‘aaaa’])?’yes ‘:’no ‘;
He got yes yes, but he didn’t say what version of PHP he was using.
I tried this on PHP 5.0.5 and got: yes no
But on PHP 4.3.5 I got: yes yes
Any foreach or similar will be different before and after the call.
To organize some of the frequently used functions..
Return Values :
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
isset expects the variable sign first, so you can’t add parentheses or anything.
With this simple function you can check if an array has some keys:
If you regard isset() as indicating whether the given variable has a value or not, and recall that NULL is intended to indicate that a value is _absent_ (as said, somewhat awkwardly, on its manual page), then its behaviour is not at all inconsistent or confusing.
Here is an example with multiple parameters supplied
= array();
$var [ ‘val1’ ] = ‘test’ ;
$var [ ‘val2’ ] = ‘on’ ;
The following code does the same calling «isset» 2 times:
= array();
$var [ ‘val1’ ] = ‘test’ ;
$var [ ‘val2’ ] = ‘on’ ;
Note that isset() is not recursive as of the 5.4.8 I have available here to test with: if you use it on a multidimensional array or an object it will not check isset() on each dimension as it goes.
Imagine you have a class with a normal __isset and a __get that fatals for non-existant properties. isset($object->nosuch) will behave normally but isset($object->nosuch->foo) will crash. Rather harsh IMO but still possible.
// pretend that the methods have implementations that actually try to do work
// in this example I only care about the worst case conditions
// if property does not exist <
echo «Property does not exist!» ;
exit;
// >
>
$obj = new FatalOnGet ();
Uncomment the echos in the methods and you’ll see exactly what happened:
On a similar note, if __get always returns but instead issues warnings or notices then those will surface.
The following is an example of how to test if a variable is set, whether or not it is NULL. It makes use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL will not.
The problem is, the set_error_handler and restore_error_handler calls can not be inside the function, which means you need 2 extra lines of code every time you are testing. And if you have any E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they will not be dealt with properly. One solution:
?>
Outputs:
True False
Notice: Undefined variable: j in filename.php on line 26
This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an E_NOTICE error happens, the file it originated from will be loaded into an array.
How to tell whether a variable is null or undefined in php
Is there a single function that can be created to tell whether a variable is NULL or undefined in PHP? I will pass the variable to the function (by reference if needed) but I won’t know the name of the variable until runtime.
isset() and is_null() do not distinguish between NULL and undefined.
array_key_exists requires you to know the name of the variable as you’re writing your code.
And I haven’t found a way to determine the name of a variable without defining it.
I’ve also realized that passing a variable by reference automatically defines it.
Elaboration
Through the collection of these answers and comments I’ve determined that the short answer to my question is «No». Thank you for all the input.
Here are some details on why I needed this:
8 Answers 8
we can differentiate it:
we can use array_key_exists(. get_defined_vars()) and is_null(. ) to detect both situations
You can’t wrap this kind of logic in a function or method as any variable defined in a function signature will be implicitly «set». Try something like this (contains code smell)
One way is if you have the variable in an array of some sort:
The alternative method I’ve come up with for figuring out whether the variable was set is a bit more involved, and really unnecessary unless this is a feature that you absolutely have to have (in which case you should be able to build it without too much difficulty).
It’s a dirty-nasty-hack if you ask me, and completely unnecessary, as null should be considered the same as an unset variable.
is_null
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
is_null — Проверяет, является ли значение переменной равным null
Описание
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования is_null()
Смотрите также
User Contributed Notes 9 notes
Micro optimization isn’t worth it.
You had to do it ten million times to notice a difference, a little more than 2 seconds
$a===NULL; Took: 1.2424390316s
is_null($a); Took: 3.70693397522s
difference = 2.46449494362
difference/10,000,000 = 0.000000246449494362
The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters.
In PHP 7 (phpng), is_null is actually marginally faster than ===, although the performance difference between the two is far smaller.
the following will prove that:
?>
this will print out something like:
10 // null
01 // true
01 // false
01 // 0
01 // 1
01 // »
01 // «\0»
Notice: Undefined variable: var in /srv/www/htdocs/sandbox/null/nulltest.php on line 8
10 // (unset)
For the major quirky types/values is_null($var) obviously always returns the opposite of isset($var), and the notice clearly points out the faulty line with the is_null() statement. You might want to examine the return value of those functions in detail, but since both are specified to return boolean types there should be no doubt.
A second look into the PHP specs tells that is_null() checks whether a value is null or not. So, you may pass any VALUE to it, eg. the result of a function.
isset() on the other hand is supposed to check for a VARIABLE’s existence, which makes it a language construct rather than a function. Its sole porpuse lies in that checking. Passing anything else will result in an error.
Knowing that, allows us to draw the following unlikely conclusion:
isset() as a language construct is way faster, more reliable and powerful than is_null() and should be prefered over is_null(), except for when you’re directly passing a function’s result, which is considered bad programming practice anyways.