PHP學習(4)——數據類型

PHP 支持 8 種原始數據類型。

四種標量類型:(標量類型即爲基本類型)

  • boolean(布爾型)
  • integer(整型)
  • float(浮點型,也稱作 double) (由於歷史原因,float也叫作double,php中沒有單精度和雙精度之分)
  • string(字符串) (字符串類型在PHP中屬於標量類型,在Java中屬於類類型)

兩種複合類型:

  • array(數組)
  • object(對象)

最後是兩種特殊類型:

  • resource(資源)
  • NULL(無類型)

變量的類型通常不是由程序員設定的,確切地說,是由 PHP 根據該變量使用的上下文在運行時決定的。

如果想查看某個表達式的值和類型,用 var_dump() 函數。
如果只是想得到一個易讀懂的類型的表達方式用於調試,用 gettype() 函數。要查看某個類型,不要用 gettype(),而用 is_type 函數。

例子:

<?php
$a_bool = TRUE;   // a boolean
$a_str  = "foo";  // a string
$a_str2 = 'foo';  // a string
$an_int = 12;     // an integer
$a_float = 3.14;  // a float(double)

echo gettype($a_bool)."<br>"; // prints out:  boolean
echo gettype($a_str)."<br>";  // prints out:  string
echo gettype($an_int)."<br>";  // prints out:  integer
echo gettype($a_float)."<br>";  // prints out:  double

// If this is an integer, increment it by four
if (is_int($an_int)) {
    echo "an_int = ".$an_int."<br>";
    $an_int += 4;
    echo "an_int = ".$an_int."<br>";
}

// If $bool is a string, print it out
// (does not print out anything)
if (is_string($a_str)) {
    echo "String: $a_str"."<br>";
}

echo var_dump($a_float, $a_bool, $a_str, $an_int);

?>

輸出:

boolean
string
integer
double
an_int = 12
an_int = 16
String: foo
float(3.14) bool(true) string(3) "foo" int(16)

php手冊中對gettype()的解釋(請放大查看☺):
這裏寫圖片描述

每種類型的具體使用,請參考PHP的官方手冊,我這裏也只是拋磚引玉。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章