2024-07-10|閱讀時間 ‧ 約 27 分鐘

PHP入門-Day4:資料型別

內建型別

PHP支持多種內建型別,主要包括以下幾類:

整數(Integer):用於表示整數值。

$intVar = 42;

浮點數(Float/Double):用於表示帶小數點的數值。

$floatVar = 3.14;

布爾值(Boolean):用於表示真(true)或假(false)。

$boolVar = true;

字符串(String):用於表示一串字符。

$stringVar = "Hello, World!";

數組(Array):用於存儲一組值。

$arrayVar = array(1, 2, 3);

對象(Object):用於表示類的實例。

class Car {
public $color;
public function __construct($color) {
$this->color = $color;
}
}
$objVar = new Car("red");

空(NULL):用於表示變數沒有值。

$nullVar = null;

資源(Resource):用於表示外部資源(如數據庫連接)。

$resourceVar = fopen("file.txt", "r");

型別轉換

隱式轉換

PHP會在需要時自動進行型別轉換(隱式轉換)。例如,將數字和字符串相加時,PHP會自動將字符串轉換為數字:

$sum = 10 + "20"; // $sum的值為30,字符串"20"被轉換為數字20

顯式轉換

顯式轉換是指開發者主動進行型別轉換。可以使用類似(int)(float)(string)等來進行顯式轉換:

$var = "100";
$intVar = (int)$var; // 將字符串轉換為整數
$floatVar = (float)$var; // 將字符串轉換為浮點數

自訂型別

PHP支持自定義類來創建自訂型別:

class Person {
public $name;
public $age;

public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

public function greet() {
return "Hello, my name is {$this->name} and I am {$this->age} years old.";
}
}

$person = new Person("Alice", 30);
echo $person->greet();

元組型別

PHP本身並不直接支持元組,但可以使用數組或對象來模擬元組的行為:

$tuple = array("Alice", 30);
echo "Name: " . $tuple[0] . ", Age: " . $tuple[1];

或者使用具名元組(關聯數組):

$tuple = array("name" => "Alice", "age" => 30);
echo "Name: " . $tuple["name"] . ", Age: " . $tuple["age"];

集合型別

PHP 7.4引入了Typed Properties,但PHP本身沒有內建的集合型別。可以使用數組或SplObjectStorage類來模擬集合:

$set = array();
$set["apple"] = true;
$set["banana"] = true;

if (isset($set["apple"])) {
echo "Apple is in the set";
}

或者使用SplObjectStorage來存儲對象集合:

$set = new SplObjectStorage();

$obj1 = new stdClass;
$obj2 = new stdClass;

$set->attach($obj1);
$set->attach($obj2);

if ($set->contains($obj1)) {
echo "Object 1 is in the set";
}

陣列型別

PHP中的數組是一種非常強大的數據結構,可以作為索引數組或關聯數組使用:

索引數組

$indexedArray = array(1, 2, 3, 4, 5);
echo $indexedArray[0]; // 輸出:1

關聯數組

$assocArray = array(
"name" => "Alice",
"age" => 30,
"email" => "alice@example.com"
);
echo $assocArray["name"]; // 輸出:Alice

字典型別

字典通常是指鍵值對的集合,在PHP中可以通過關聯數組來實現:

$dict = array(
"name" => "Alice",
"age" => 30,
"email" => "alice@example.com"
);

foreach ($dict as $key => $value) {
echo "$key: $value\\\\n";
}

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.