發新話題

[分享] 《資訊分享》 PHP 手冊 - 語法 『資料型態』

《資訊分享》 PHP 手冊 - 語法 『資料型態』

PHP提供八種資料型態,分別是:布林值、整數值、浮點數、字串、陣列、物件、resource、NULL。在手冊裡,你會發現mixed這種參數,它表示這個參數的值可能具有多樣性的型態。如果你想要改變變數的型態,你可以使用settype( )的方式,或是以直接指定的方式來設定。

一、布林值

這種型態的值可以是TRUE或FALSE其中之一。

語法
它的值以是TRUE或FALSE,這二個值都是沒有區分大小寫的。

$foo = True; // assign the value TRUE to $foo

布林值也可以使用在控制迴圈裡面,如下面範例所示:

// == is an operator which returns a boolean
if ($action == "show_version") {
    echo "The version is 1.23";
}

// this is not necessary:
if ($show_separators == TRUE) {
    echo "<hr>\n";
}

// because you can simply type this:
if ($show_separators) {
    echo "<hr>\n";
}

轉換成布林值
要將其它型態的值轉換成布林值,可以使用(bool)或(boolean)其中之一的方式來作轉換。若要轉換成布林值,下列這些值都將被視為FALSE,其餘的將視為TRUE。

the boolean FALSE

the integer 0 (zero)

the float 0.0 (zero)

the empty string, and the string "0"

an array with zero elements

an object with zero elements

the special type NULL (including unset variables)

 

二、整數值

整數值的範圍是Z = {..., -2, -1, 0, 1, 2, ...}。

語法
整數值可以是十進位、十六進位、八進位的值,如果你是使用八進位的值,你必需在數字前面加上一個零(0),如果是使用十六進位,則必需加上0x。

Example:

$a = 1234; # decimal number
$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x1A; # hexadecimal number (equivalent to 26 decimal)

溢位的整數值
如果你所指定的數字,超出整數值的範圍,這個數字將被視為浮點數。見以下範例:

$large_number =  2147483647;
var_dump($large_number);
// output: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648)

// this goes also for hexadecimal specified integers:
var_dump( 0x80000000 );
// output: float(2147483648)

$million = 1000000;
$large_number =  50000 * $million;
var_dump($large_number);
// output: float(50000000000)

若以分數表示,1/2所產生出來的結果會是浮點數0.5。

var_dump( 25/7 );
// output: float(3.5714285714286)

轉換成整數值
要將其它型態的值轉換成整數值,可以使用(int)或(integer)其中之一的方式來作轉換。

從布林值轉換:FALSE會被視為零(0),TRUE會被視為1。

從浮點數轉換:小數點後的值會被省略掉。

 

三、浮點數

浮點數又稱為floats、doubles、real numbers。可使用下列語法來設定它的值:

$a = 1.234; $a = 1.2e3; $a = 7E-10;

 

四、字串

字串的表達方式有三種:單引號、雙引號、heredoc語法。

單引號
這種方式相當的簡單,只需在字串的前後加上單引號( ' )即可。若字串中含有單引號,那麼你必需使用反斜線(\)來將它逃脫,如果需要在字串的結尾處出現反斜線字元,則必需再加上一個反斜線。如果你試著要去逃脫其它的字元,反斜線也會被顯示出來,所以要顯示出反斜線本身的字元,就不用再將它逃脫。

echo 'this is a simple string';
echo 'You can also have embedded newlines in strings,
like this way.';
echo 'Arnold once said: "I\'ll be back"';
// output: ... "I'll be back"
echo 'Are you sure you want to delete C:\\*.*?';
// output: ... delete C:\*.*?
echo 'Are you sure you want to delete C:\*.*?';
// output: ... delete C:\*.*?
echo 'I am trying to include at this point: \n a newline';
// output: ... this point: \n a newline

雙引號
若將字串以雙引號( " )圍住,PHP所能逃脫的字元會變得更多。同樣的,如果你試著要去逃脫其它的字元,反斜線也會被顯示出來。如下列所示:

sequence meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

Heredoc
另一種表達字串的方式,是使heredoc語法("<<<")。在<<<後面必需給一個指標,然後才是字串本身,最後還要以相同的指標來將它結束。作為結束的指標必需是相同的名稱,它可以是字母與數字結合起來的字串及"_"這個符號,但不能以一個非數字的字元或"_"做為開頭。

使用Heredoc和使用雙引號這二種方式,其實都是差不多的。使用heredoc的語法,就不用再將字串中的引號逃脫。

Example:

<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var $foo;
    var $bar;

    function foo()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

剖析字串中的變數
下列有二種方式可以剖析字串中的變數。

第一種方式:當剖析器遇到錢($)的符號時,會把它當是一個變數名稱,你也可以使用大括弧將變數的名稱給括弧起來。如下面範例所示:

$beer = 'Heineken';
echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drunk some $beers"; // won't work, 's' is a valid character for varnames
echo "He drunk some ${beer}s"; // works

同樣地,在字串中也可以使用陣列的索引值或物件,要使要陣列的索引值,必需以中括弧將它括弧起來。如下面範例所示:

$fruits = array( 'strawberry' => 'red' , 'banana' => 'yellow' );

// note that this works differently outside string-quotes.
echo "A banana is $fruits[banana].";

echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";

第二種方式:這種方式的語法比較複雜一點,可是使用這種方式,可以讓你含括更複雜的表達示。如下面範例所示:

$great = 'fantastic';
echo "This is { $great}"; // won't work, outputs: This is { fantastic}
echo "This is {$great}";  // works, outputs: This is fantastic
echo "This square is {$square->width}00 centimeters broad.";
echo "This works: {$arr[4][3]}";     

// This is wrong for the same reason
// as $foo[bar] is wrong outside a string.
echo "This is wrong: {$arr[foo][3]}";

echo "You should do it this way: {$arr['foo'][3]}";
echo "You can even write {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";

取出字串中的字元
要取出字串中的字元,可在字串後面使用大括弧將偏移量括弧起來,就可得到該偏移量在字串中所代表的字元。偏移量的起始值為零(0),如下面範例所示:

<?php
/* Assigning a string. */
$str = "This is a string";

/* Appending to it. */
$str = $str . " with some more text";

/* Another way to append, includes an escaped newline. */
$str .= " and a newline at the end.\n";

/* This string will end up being '<p>Number: 9</p>' */
$num = 9;
$str = "<p>Number: $num</p>";

/* This one will be '<p>Number: $num</p>' */
$num = 9;
$str = '<p>Number: $num</p>';

/* Get the first character of a string  */
$str = 'This is a test.';
$first = $str{0};

/* Get the last character of a string. */
$str = 'This is still a test.';
$last = $str{strlen($str)-1};
?>

將字串連接
要將字串連接起來可以使用點( . )這個運算子,而不是使用加號(+)。

轉換字串
如果字串中包含了'.'、'e'、'E'這些字元,在轉換後會視為是浮點數的值。若沒有包含那些字元,轉換後會視為是整數值。若字串的開頭是個有效的數字型態,則會使用此一數字的值,其餘的型式在轉換後的值都為零。

$foo = 1 + "10.5";              // $foo is float (11.5)
$foo = 1 + "-1.3e3";            // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";         // $foo is integer (1)
$foo = 1 + "bob3";              // $foo is integer (1)
$foo = 1 + "10 Small Pigs";     // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;        // $foo is float (11)
$foo = "10.0 pigs " + 1.0;      // $foo is float (11)

 

五、陣列

陣列型態可被array( )這個函式所建立,陣列內的內容包含了數個key => value,並以逗號將它們分隔開來。陣列的索引值可以是整數值或是字串,若是以整數值來表示索引值,它會將它解譯成數字本身所代表的意義(例如:"8"會被解譯成8,而"08"會被解譯成"08")。

如果你省略了陣列的索引值,它會取最大的整數索引值,並將此最大值再加上1後來作為索引值。你也可以使用負數來作為陣列的索引值,假設索引值的最大值為-6,則會以-5來作為索引值。假設陣列的索引值沒有任何的整數索引值,那麼它將會使用0來作為索引值。如果你所指定的索引值己經存在了,則新的值會覆蓋掉原有的值。

使用TRUE來當作是索引值會被視為是整數值1,而使用FALSE會被視為整數值0,使用NULL會被視為是空字串。

你不能使用陣列或物件來作為陣列的索引值,這樣做會導致產生出警告的訊息。

array( [key =>] value
     , ...
     )
// key is either string or nonnegative integer
// value can be anything

建立及修改陣列內容
你可以以設定新值的方式來修改陣列的內容,只要在中括弧裡面指定其索引值,就可以將新的值覆蓋掉原有的值,你也可以省略索引值,只用中括弧而己。如下面範例所示:

$arr[key] = value;
$arr[] = value;
// key is either string or nonnegative integer
// value can be anything

假設$arr不存在,它會試著去建立它。若$arr存在,它會去修改它的內容,將新的值分配給它。如果你想要移除key/value對,你可以使用unset( )這個函式將它移除。

$a = array( 1 => 'one', 2 => 'two', 3 => 'three' );
unset( $a[2] );
/* will produce an array that would have been defined as
   $a = array( 1=>'one', 3=>'three');
   and NOT
   $a = array( 1 => 'one', 2 => 'three');
*/

陣列的規則
若要指定陣列的索引值時,必需使用$foo['bar']這種方式,而不是使用$foo[bar]這種方式,如下面範例所示:

$foo[bar] = 'enemy';
echo $foo[bar];
// etc

這樣的寫法是錯誤的,不過卻還是可以運作。但為何這樣是錯誤的呢?這是因為在程式碼裡面並沒有定義bar這個常數是個字串,程式之所以能夠運作,是因為程式將這個未定義的常數自動轉換成字串,雖然程式會將它轉換成字串,但最好還是把它加上單引號會比較好。你可以在上面的範例中,加上error_reporting(E_ALL);這行,你會看到有注意的訊息產生出來了。

在PHP中,陣列是相當好用的,你可以看下面範例如何使用陣列。

Example:

// this
$a = array( 'color' => 'red'
          , 'taste' => 'sweet'
          , 'shape' => 'round'
          , 'name'  => 'apple'
          ,            4        // key will be 0
          );

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array( 0 => 'a' , 1 => 'b' , 2 => 'c' ),
// or simply array('a', 'b', 'c')

Example:

// Array as (property-)map
$map = array( 'version'    => 4
            , 'OS'         => 'Linux'
            , 'lang'       => 'english'
            , 'short_tags' => true
            );
            
// strictly numerical keys
$array = array( 7
              , 8
              , 0
              , 156
              , -10
              );
// this is the same as array( 0 => 7, 1 => 8, ...)

$switching = array(         10 // key = 0
                  , 5    =>  6
                  , 3    =>  7
                  , 'a'  =>  4
                  ,         11 // key = 6 (maximum of integer-indices was 5)
                  , '8'  =>  2 // key = 8 (integer!)
                  , '02' => 77 // key = '02'
                  , 0    => 12 // the value 10 will be overwritten by 12
                  );
                  
// empty array
$empty = array();

Example:

$colors = array('red','blue','green','yellow');

foreach ( $colors as $color ) {
    echo "Do you like $color?\n";
}

/* output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
*/

上面這個範例並不會在迴圈裡面直接地改變陣列的值,下面這個範例就會去改變陣列的值。

Example:

foreach ($colors as $key => $color) {
    // won't work:
    //$color = strtoupper($color);
   
    //works:
    $colors[$key] = strtoupper($color);
}
print_r($colors);

/* output:
Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)
*/

Example:

$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);

/* output:
Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)
*/

Example:

// fill an array with all items from a directory
$handle = opendir('.');
while ($file = readdir($handle))
{
    $files[] = $file;
}
closedir($handle);

Example:

$fruits = array ( "fruits"  => array ( "a" => "orange"
                                     , "b" => "banana"
                                     , "c" => "apple"
                                     )
                , "numbers" => array ( 1
                                     , 2
                                     , 3
                                     , 4
                                     , 5
                                     , 6
                                     )
                , "holes"   => array (      "first"
                                     , 5 => "second"
                                     ,      "third"
                                     )
                );

 

六、物件

要初始化(initialize)物件,可以使用new這個語法。

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();
?>

細節請參考類別與物件的語法。

七、resource

resource是個特殊的變數,它是被特殊的函式所建立並加以使用。

 

八、NULL

這個特殊的值NULL,所代表的意思是變數的值是空的,NULL唯一的值就是NULL。

如果變數符合下列三點之一,則變數的值會被視為是NULL:

變數的值是NULL。
變數並沒有被設定任何的值。
變數己經被unset( )這個函式所刪除了。
下列這個範例可以將變數的值被設定為NULL,NULL這個字是不區分大小寫的。

$var = NULL;

 

九、型態轉換

在宣告變數時,不需明確的指出變數的型態,變數的型態是由變數的內容所決定的,假如你分配一個字串給變數var,var就會成為一個字串型態。如果你分配一個整數值給var,它就會成為整數型態。

下面這個範例將說明使用運算元"+",自動地改變資料型態。如果在運算域裡面都是浮點數型態的值,則所有的運算域都被視為浮點數,運算後的結果也會是浮點數。其它的話,運算域都會被視為是整數值,運算後的結果也會是整數值。

$foo = "0";  // $foo is string (ASCII 48)

$foo += 2;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)

要轉換資料的型態可使用下列這種方式:

$foo = 10;   // $foo is an integer
$bar = (float) $foo;   // $bar is a float

允許轉換的種類有下列幾種:

(int), (integer) - 轉換成整數。

(bool), (boolean) - 轉換成布林值。

(float), (double), (real) - 轉換成浮點數。

(string) - 轉換成字串。

(array) - 轉換成陣列。

(object) - 轉換成物件。

在括弧裡面可以包含tabs及空白鍵,如下面範例所示,這二行的作用都是相同的。

$foo = (int) $bar;
$foo = ( int ) $bar;

要將陣列轉換成字串的話,轉換後的結果會是Array這個字。而將物件轉換成字串的話,轉換後的結果會是Object這個字。

要將一個數量或字串的變數轉換成陣列,變數的值會成為陣列的第一個元素。

$var = 'ciao';
$arr = (array) $var;
echo $arr[0];  // outputs 'ciao'

要將一個數量或字串的變數轉換成物件,變數的值會成為物件的屬性,此屬性的名稱會是'scalar'。

$var = 'ciao';
$obj = (object) $var;
echo $obj->scalar;  // outputs 'ciao'


TOP

發新話題

本站所有圖文均屬網友發表,僅代表作者的觀點與本站無關,如有侵權請通知版主會盡快刪除。