PHP Data Type

PHP Data Type

PHP 的資料型別有以下這幾種:

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

String

宣告 String 需要再 “” 或是 ‘’ 之中,兩者皆可以使用。

1
2
3
4
5
6
7
8
9
10
<?php
$x = "Hello world";
$y = 'Hello world';
echo $x;
echo "<br>";
echo $y;
// 以上兩個輸出都是 Hello world。
?>

Integer

Integer 為無小數點的整數,介於 -2,147,483,6482,147,483,647 之間,有以下這些規則:

  • 至少有一位數字
  • 不能有小數點
  • 可以為 正或是負
  • 可定義為三種格式 : 10進制, 16進制, 8進制
    1
    2
    3
    4
    5
    6
    <?php
    $x = 2048;
    var_dump($x);
    // 輸出 int(2048)
    ?>

var_dump() 可顯示傳入的變數的data type 和 value

Float

浮點數可用來 表示包含小數點的數字 和 指數。

1
2
3
4
5
6
<?php
$x = 26.975;
var_dump($x);
// 輸出為 float(26.975)
?>

Boolean

布林 只代表兩種狀態: TRUE or FALSE。

1
2
3
4
<?php
$x = true;
$y = false;
?>

Array

陣列的功能是 可以儲存多個variable 在它之中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// PHP 5.3以前的寫法
$cars = array("Volvo","Audi","Tesla");
// PHP 5.4以後的寫法
$cars2 = array [
0 => "Volvo",
1 => "Audi",
2 => "Tesla"
]
var_dump($cars);
// 輸出為 array(3) {[0]=> string(5)"Volvo" [1]=> string(4)"Audi" [2]=> string(5)"Tesla"}
?>

Object

Object身上可包含許多data type,而 Object 是由 class 產生出來的實體(instance),class 中定義了 properties 和 methods。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
class Cars {
function Car() {
$this->model = "VW";
}
// Create an object
$myCar = new Car();
// Show object properties
echo $myCar->model;
// 輸出結果 VW
}
?>

NULL

NULL 是特殊的data type,它只有一種值那就是:NULL。

如果 variable 宣告時,沒有賦值系統會自動設定 NULL 給此 variable。

1
2
3
4
5
6
<?php
$x = "Hello world";
$x = null;
echo var_dump($x);
// 輸出結果:NULL
?>

Resources

暫時不理解這個type…放上官方英文解說。

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.

Casting

各data type轉型的用法如下:

  • (int),(integer) - cast to integer
  • (bool),(booleab) - cast to boolean
  • (float),(double),(real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL
    1
    2
    3
    4
    <?php
    $var = "100";
    $cast = (int)$var;
    ?>