PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Булев тип> <Коментари
Last updated: Fri, 05 Dec 2008

view this page in

Типове

Съдържание

Въведение

PHP поддържа осем примитивни типа.

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

  • булев (boolean)
  • целочислен (integer)
  • плаващ (float) (числа с плаваща запетая, също познати като double)
  • низ (string)

Два съставни типа:

  • масив (array)
  • обект (object)

И накрая, два специални типа:

  • ресурс (resource)
  • NULL

Това ръководство въвежда също и някои псевдо-типове с цел - по-добра четимост:

  • смесен (mixed)
  • число (number)
  • обратно извикване (callback)

И псевдо-променливата $... .

Възможно е да се натъкнете също и на препратки към типа "double" (двоен). Разглеждайте го като число с плаваща запетая (float), двете имена съществуват единствено по исторически причини.

Типът на променливата обикновено не се указва от програмиста; по-често, той се решава по време на изпълнение от PHP в зависимост от контекста, в който е използвана тази променлива.

Забележка: Ако искате да разберете типа и стойността на даден израз, използвайте var_dump(). Ако желаете човешко представяне на типа, с цел откриване на грешки, използвайте gettype(). За да проверите даден тип, не използвайте gettype(), а функциите is_type. Няколко примера:

<?php
$a_bool 
TRUE;   // булев
$a_str  "foo";  // низ
$an_int  12;     // цяло число

echo gettype($a_bool); // отпечатва "boolean"
echo gettype($a_str);  // отпечатва "string"

// Ако това е цяло число, увеличи го с четири
if (is_int($an_int)) {
    
$int += 4;
}

// Ако $a_bool е низ го отпечатай на екрана
// (does not print out anything)
if (is_string($a_bool)) {
    echo 
"Низ: $a_bool";
}
?>

Ако искате изрично да превърнете променлива в даден тип, можете или да я преобразувате, или да използвате функцията settype() върху нея.

Забележете, че в някои случаи променливата може да бъде изчислена по различен начин, в зависимост от това какъв е типът й в момента. За повече информация, вижте раздела за Манипулации с типове. Също, би представлявало интерес за вас да разгледате таблицата за сравнение на типовете, тъй като там има примери за най-различни сравнения, свързани с типовете.



Булев тип> <Коментари
Last updated: Fri, 05 Dec 2008
 
add a note add a note User Contributed Notes
Типове
Jeffrey
26-Oct-2008 11:31
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: http://www.php.net/manual/en/language.oop5.php
jonah_whalehosting_ca
12-Apr-2007 10:33
In reply to Philip, form data could also be an array.  so there are two types you can expect from $_REQUEST (and it's associates): string and array.
arjini at gmail dot com
06-Dec-2005 12:32
Note that you can chain type castng:

var_dump((string)(int)false); //string(1) "0"
shahnaz khan
18-Mar-2005 04:40
if we use gettype() before initializinf any variable it give NULL
for eg.

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

it will show

NULL
Trizor of www.freedom-uplink.org
29-Jun-2004 06:14
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.

Булев тип> <Коментари
Last updated: Fri, 05 Dec 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites