Php what is null

PHP Data Types

Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

  • String
  • Integer
  • Float (floating point numbers — also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

PHP String

A string is a sequence of characters, like «Hello world!».

A string can be any text inside quotes. You can use single or double quotes:

Example

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

  • An integer must have at least one digit
  • An integer must not have a decimal point
  • An integer can be either positive or negative
  • Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation

In the following example $x is an integer. The PHP var_dump() function returns the data type and value:

Example

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential form.

In the following example $x is a float. The PHP var_dump() function returns the data type and value:

Example

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.

PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data type and value:

Example

You will learn a lot more about arrays in later chapters of this tutorial.

PHP Object

Classes and objects are the two main aspects of object-oriented programming.

A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

Let’s assume we have a class named Car. A Car can have properties like model, color, etc. We can define variables like $model, $color, and so on, to hold the values of these properties.

Читайте также:  Полная установка php ubuntu

When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

Example

class Car public $color;
public $model;
public function __construct($color, $model) $this->color = $color;
$this->model = $model;
>
public function message() return «My car is a » . $this->color . » » . $this->model . «!»;
>
>

$myCar = new Car(«black», «Volvo»);
echo $myCar -> message();
echo «
«;
$myCar = new Car(«red», «Toyota»);
echo $myCar -> message();
?>

PHP NULL Value

Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

Example

PHP Resource

The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.

A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

Источник

Что такое null и как с этим жить: сравнение с null в PHP, тонкости в приведении типов данных

В работе с любыми данными то и дело требуется как-то обозначить их отсутствие. Новички зачастую для этой цели используют значение false, которое, по сути, является не отсутствием данных, а определённым значением типа boolean. Для того, чтобы как-то помечать неопределённость или отсутствие данных, существует специальное значение null. Про false, null и прочее уже немало сказано и добавить что-то оригинальное крайне сложно. Но гораздо сложнее бывает найти баг, вызванный неочевидным поведением этих штуковин. Поэтому, вдохновлённый одним таким багом, самым элегантным в моём послужном списке, я решил написать маленькую шпаргалку на эту тему.

Перегружать пост интересными, но довольно-таки бесполезными определениями из Википедии я не стану. Вместо этого перейду сразу к делу и приведу цитату со страницы php.net, посвящённой null:

  • ей была присвоена константа NULL.
  • ей еще не было присвоено никакого значения.
  • она была удалена с помощью unset().

До этого момента всё кажется простым, но чтобы так оставалось и дальше, при работе с null нужно придерживаться определённых правил.

Математические операции с null

Во всех математических операциях null ведёт себя аналогично int(0):

 $a = null; $a + 1; // int(1) $a - 1; // int(-1) $a * 1; // int(0) 1 / $a; // bool(false) 

Проверка переменной на null

Чтобы точно узнать, что переменная содержит null (то есть, ничего не содержит), нужно использовать либо специальную функцию is_null() либо тождественное сравнение ===, а любые другие способы не подойдут:

 // Правильная проверка переменной на null $a = null; is_null($a); // bool(true) $a === null; // bool(true) 

Проверка null if-выражениях, а так же в функциях empty() и isset()

Тут переменные с null ведут себя абсолютно предсказуемо, как и любые другие ложные значения (которые в if-выражениях приводятся к false). Но нужно помнить, что это не гарантирует нам, что в переменной находится именно null:

 // В if-выражениях null приводится к false, как и все другие ложные значения if($a) < echo 'Sure, $a is not null!'; >else < echo 'Mabye $a is null.' >// Проверка на empty() вернёт true, но не гарантирует, что проверяемая переменная - именно null $a = null; empty($a); // bool(true) $a = []; empty($a); // bool(true) $a = ''; empty($a); // bool(true) $a = 0; empty($a); // bool(true) $a = false; empty($a); // bool(true) // Проверка isset() вернёт false не только для null, но для не определённой переменной $a = null; isset($a); // bool(false) isset($undefined); // bool(false) 

Сравнение двух null

В PHP как гибкое, так и тождественное сравнение двух null всегда возвращает false, в отличие от многих других платформ, где сравнение двух неизвестностей возвращает так же неизвестность (то есть, null).

 // PHP уверен, что две неизвестности равны, и даже тождественно равны $a = null; $b = null; $a == $b; // bool(true) $a === $b; // bool(true) 

Поведение null при нетождественном сравнении с приведением типов данных

PHP разрешает сравнивать null-ы не только между собой, но и с другими типами данных. При этом не стоит забывать, что гибкое сравнение в php не является транзитивным, то есть, если два значения равны третьему по отдельности, не гарантирует их равенство между собой. Согласно таблицам приведения типов, гибкое сравнение null при помощи оператора == с разными значениями возвращает разные результаты:

 // Для всех ложных значений гибкое сравнение с null возвращает true, кроме строки '0' $a = []; $a == null; // bool(true) $a = ''; $a == null; // bool(true) $a = 0; $a == null; // bool(true) $a = false; $a == null; // bool(true) // А при сравнении null со строкой '0' мы получим false, хотя null == false и '0' == false $a = '0'; $a == null; // bool(false) // Для всех неложных значений такое сравнение так же вернёт false $a = 1; $a == null; // bool(false) $a = '1'; $a == null; // bool(false) 

Сравнение с null с помощью >, =, PHP -> JavaScript) поведение null может меняться.

Исследование null в JavaScript (а вместе с ним и загадочного undefined) заслуживает отдельной статьи. Главное отличие состоит в том, что, не смотря на приведение типов, null в JavaScript ничему не равен, кроме самого null и этого самого undefined, хотя в if-выражениях и срабатывает аналогично false. А при сравнении с числами он выдаёт ещё более забавные результаты, чем в PHP.

Читайте также:  Php xpath a href

NULL в MySQL, к примеру, действует гораздо более прямолинейно. Он просто при любых действиях с null (даже при сравнении двух null) возвращает null. С его точки зрения, при любых действиях с неизвестностью в результате получится какая-то другая неизвестность 🙂

Простое правило при работе null, которое помогает избегать проблем

Вообще-то, не стоило читать этот пост. Держать в голове все эти нюансы, которые разные платформы трактуют по-разному, — неблагодарное занятие. Для того, чтобы избежать проблем с null нужно запомнить всего лишь одно правило:

Старайтесь не выполнять с null никаких лишних действий: не нужно его ни с чем сравнивать, складывать, сортировать. Там, где чисто теоретически переменная с null может просочиться в какие-то операторы, лучшим решением будет сперва проверить её функцией is_null(). 08.04.2014 © mithrandir.ru

Источник

PHP null

Summary: in this tutorial, you will learn about the PHP NULL type and how to check if a variable is null or not.

Introduction to the PHP null type

The null is a special type in PHP. The null type has only one value which is also null . In fact, null indicates the absence of a value for a variable.

A variable is null when you assign null to it like this:

 $email = null; var_dump($email); // NULLCode language: HTML, XML (xml)

In addition, when you use the unset() function to unset a variable, the variable is also null. For example:

 $email = 'webmaster@phptutorial.net'; unset($email); var_dump($email); // NULLCode language: HTML, XML (xml)

PHP NULL and case-sensitivity

PHP keywords are case-insensitive. Therefore, NULL is also case-insensitive. It means that you can use null , Null , or NULL to represent the null value. For example:

 $email = null; $first_name = Null; $last_name = NULL;Code language: HTML, XML (xml)

It’s a good practice to keep your code consistent. If you use null in the lowercase in one place, you should also use it in your whole codebase.

Testing for NULL

To check if a variable is null or not, you use the is_null() function. The is_null() function returns true if a variable is null ; otherwise, it returns false . For example:

 $email = null; var_dump(is_null($email)); // bool(true) $home = 'phptutorial.net'; var_dump(is_null($home)); // bool(false)Code language: HTML, XML (xml)

To test if a variable is null or not, you can also use the identical operator === . For example:

 $email = null; $result = ($email === null); var_dump($result); // bool(true) $home= 'phptutorial.net'; $result = ($home === null); var_dump($result); // bool(false)Code language: HTML, XML (xml)

Summary

  • PHP null type has a value called null that represents a variable with no value.
  • Use the is_null() function or === operator to compare a variable with null.

Источник

Оцените статью