ตัวแปร ในภาษา PHP คือตัวเก็บข้อมูล มีไว้เก็บค่าต่างๆ เช่น ตัวเลข สตริง อาร์เรย์ ออบเจ็กต์ ฯลฯ
การประกาศตัวแปร:
- เริ่มต้นด้วยเครื่องหมาย
$
- ตามด้วยชื่อตัวแปร
- กำหนดค่าให้กับตัวแปร (ไม่จำเป็น)
ตัวอย่าง:
PHP
$name = "John Doe"; // ประกาศตัวแปร name เก็บค่า "John Doe"
$age = 30; // ประกาศตัวแปร age เก็บค่า 30
ประเภทข้อมูล:
PHP มีประเภทข้อมูลหลักๆ ดังนี้
- Integer: ตัวเลขเต็ม เช่น 1, 2, 3
- Float: ตัวเลขทศนิยม เช่น 3.14, 1.5
- String: ข้อความ เช่น “Hello World!”
- Boolean: ค่า TRUE หรือ FALSE
- Array: เก็บข้อมูลชุด เช่น [“apple”, “banana”, “orange”]
- Object: เก็บข้อมูลแบบออบเจ็กต์
การตรวจสอบประเภทข้อมูล:
ใช้ฟังก์ชั่น gettype()
PHP
$name = "John Doe";
echo gettype($name); // แสดงผล "string"
การแปลงประเภทข้อมูล:
- ฟังก์ชั่น
settype()
- ฟังก์ชั่น
intval()
- ฟังก์ชั่น
floatval()
- ฟังก์ชั่น
strval()
ตัวอย่าง:
PHP
$age = "30";
$age = intval($age); // แปลง "30" เป็น integer
$price = 10.5;
$price = strval($price); // แปลง 10.5 เป็น string
เพิ่มเติม:
- PHP เป็นภาษาแบบ dynamically typed ไม่จำเป็นต้องระบุประเภทข้อมูล
- ประเภทข้อมูลจะถูกกำหนดโดยอัตโนมัติจากค่าที่กำหนดให้
- การแปลงประเภทข้อมูลอาจทำให้ข้อมูลสูญเสียความแม่นยำ
แหล่งข้อมูล:
- W3Schools: https://www.w3schools.com/php/php_variables.asp
- PHP.net: https://www.php.net/manual/en/language.variables.basics.php
- Tutorialzine: https://irinagyurjinyan.wordpress.com/2022/04/12/%D1%83%D1%80%D0%BE%D0%BA-19/