中央論壇 - CENTER BBS

標題: 變數型態轉換 - PHP 的型別轉換 [打印本頁]

作者: 郭子錢    時間: 2014-7-25 11:03
標題: 變數型態轉換 - PHP 的型別轉換
本帖最後由 郭子錢 於 2014-7-25 11:05 編輯

PHP 變數要做強迫轉換變數型態的方法有兩種:

1. 使用 C 語言 type casting 語法,例如:
  1. $x = 3;
  2. $y = (double) $x;                //括弧裡可以有 tab 或空白 (space)
複製代碼
可使用的 cast 型別有:

1. (int),(integer) - 轉換成 integer 型別
2. (bool),(boolean) - 轉換成 boolean 型別
3. (float),(double),(real) - 轉換成 float 型別
4. (string) - 轉換成 string 型別
5. (array) - 轉換成 array 型別
6. (object) - 轉換成 object 型別


type casting 型別轉換範例。範例 1:

  1. <?php
  2. $x = "3";
  3. $number = (int)$x;
  4. echo $number; //輸出 3
  5. ?>
複製代碼
範例 2:

  1. <?php
  2. $x = "a1";
  3. $arr = (array)$x;
  4. echo $arr[0]; //輸出 "a1"
  5. ?>
複製代碼
範例 3:

  1. <?php
  2. $x = "a1";
  3. $obj = (object)$x;
  4. echo $obj->scalar; //輸出 "a1"
  5. ?>
複製代碼


2. 使用 settype 函數:

int settype(string var, string type);
將 var 變數轉換為 type 型別,可指定的型別參數有:

1. "boolean" (PHP 4.2.0 與之後的版本也可以簡寫成 "bool")
2. "integer" (PHP 4.2.0 與之後的版本也可以簡寫成 "int")
3. "float" (PHP 4.2.0 與之後的版本才支援)
4. "double"
5. "string"
6. "array"
7. "object"
8. "null" (PHP 4.0.8 以後的版本才支援)


轉換成功傳回 true,否則傳回 false。當我們不知道某個變數的值是什麼型別時,也可以利用 gettype() 函數來取得。

在 PHP 裡和 C 語言一樣,非零即為 true,例如 if ($x) 等於 if ($x != 0)。




歡迎光臨 中央論壇 - CENTER BBS (https://www.centerbbs.com/) Powered by Discuz! X3