Типы

Содержание

Введение

PHP поддерживает восемь простых типов.

Четыре скалярных типа:

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

Как правило, программист не устанавливает тип переменной; предпочтительнее, чтобы это делал PHP во время выполнения программы в зависимости от контекста, в котором используется переменная.

Замечание: Если вы желаете проверить тип и значение определенного выражения, используйте var_dump(). Если же вам для отладки необходимо просто удобочитаемое представление типа, используйте gettype(). Чтобы проверить на определенный тип, не используйте gettype(), применяйте для этого is_type функции. Вот несколько примеров:

<?php
$bool 
TRUE;   // логический
$str  "foo";  // строковый
$int  12;     // целочисленный

echo gettype($bool); // выводит "boolean"
echo gettype($str);  // выводит "string"

// Если это целое, увеличить на четыре
if (is_int($int)) {
    
$int += 4;
}

// Если $bool - это строка, вывести ее
// (ничего не выводит)
if (is_string($bool)) {
    echo 
"Строка: $bool";
}
?>

Если вы хотите принудительно изменить тип переменной, вы можете либо привести переменную, либо использовать функцию settype().

Обратите внимание, что переменная, в зависимости от ее типа в данный момент, в определенных ситуациях может иметь разные значения. Более подробную информацию смотрите в разделе Манипуляции с типами. Также вам, возможно, будет интересно посмотреть таблицы сравнения типов, поскольку в них приведены примеры связанных сравнений различных типов.

Коментарии

The differance of float and double dates back to a FORTRAN standard. In FORTRAN Variables aren't as loosly written as in PHP and you had to define variable types(OH NOES!). FLOAT or REAL*4 (For all you VAX people out there) defined the variable as a standard precision floating point, with 4 bytes of memory allocated to it. DOUBLE PRECISION or REAL*8 (Again for the VAX) was identical to FLOAT or REAL*4, but with an 8 byte allocation of memory instead of a 4 byte allocation.

In fact most modern variable types date back to FORTRAN, except a string was called a CHARACHTER*N and you had to specify the length, or CHARACHTER*(*) for a variable length string. Boolean was LOGICAL, and there weren't yet objects, and there was support for complex numbers(a+bi).

Of course, most people reading this are web programmers and could care less about the mathematical background of programming.

NOTE: Object support was added to FORTRAN in the FORTRAN90 spec, and expanded with the FORTRAN94 spec, but by then C was the powerful force on the block, and most people who still use FORTRAN use the FORTRAN77.
2004-06-29 21:14:23
http://php5.kiev.ua/manual/ru/language.types.html
Автор:
if we use gettype() before initializinf any variable it give NULL
for eg.

<?php
$foo
;
echo 
gettype($foo);
?>

it will show 

NULL
2005-03-18 06:40:59
http://php5.kiev.ua/manual/ru/language.types.html
Note that you can chain type castng:

var_dump((string)(int)false); //string(1) "0"
2005-12-06 14:32:20
http://php5.kiev.ua/manual/ru/language.types.html
Автор:
The Object (compound) Type

Like every programming language, PHP offers the usual basic primitive types which can hold only one piece of data at a time (scalar). I am particularly fond of the "object" type (compound) because that allows me to group many basic PHP types together, and I can name it anything I want.

<?php
class Person
{
 
$firstName;                   // a PHP String
 
$middleName;                  // a PHP String
 
$lastName;                    // a PHP String
 
$age;                         // a PHP Integer
 
$hasDriversLicense;           // a PHP Boolean 
}
?>

Here, I have grouped several basic PHP types together, (3) Strings, (1) Integer, and (1) Boolean... then I named that group "Person". Since I used the proper syntax to do so, this code is pure PHP, which means that if you run this code, you would have an extra PHP "type" available to you in your scripts, like so:

<?php
$myAge 
16;                    // a PHP Integer - always available
$yourAge 15.5;                // a PHP Float   - always available
$hasHair true;                // a PHP Boolean - always available
$greeting "Hello World!"      // a PHP String  - always available

$person = new Person();         // a PHP Person  - available NOW!
?>

You can make your own object types and have PHP execute it as if it were part of the PHP language itself. See more on classes and objects in this manual at: language.oop5
2008-10-26 12:31:06
http://php5.kiev.ua/manual/ru/language.types.html

    Поддержать сайт на родительском проекте КГБ