что такое isset в php

isset — Определяет, была ли установлена переменная значением отличным от NULL

Описание

Определяет, была ли установлена переменная значением отличным от NULL

Если были переданы несколько параметров, то isset() вернет TRUE только в том случае, если все параметры определены. Проверка происходит слева направо и заканчивается, как только будет встречена неопределенная переменная.

Список параметров

Возвращаемые значения

Список изменений

Примеры

Пример #1 Пример использования isset()

// В следующем примере мы используем var_dump для вывода
// значения, возвращаемого isset().

$a = «test» ;
$b = «anothertest» ;

Функция также работает с элементами массивов:

Пример #2 isset() и строковые индексы

Результат выполнения данного примера в PHP 5.3:

Результат выполнения данного примера в PHP 5.4:

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

При использовании isset() на недоступных свойствах объекта, будет вызываться перегруженный метод __isset(), если он существует.

Смотрите также

Источник

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.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

ВерсияОписание
5.4.0