บทนำ
Class เป็น User-defined Data Type ใน PHP ใช้คีย์เวิร์ด class ตามด้วยชื่อคลาส ชื่อที่ถูกต้องตาม Naming Convention ของ PHP (ยกเว้น Reserved Words) ส่วนประกอบของคลาสอยู่ใน Curly Braces
Syntax
class myclass {
// properties, constants, methods
}
คลาสประกอบด้วย:
- Constants - ค่าคงที่ (const)
- Properties - ตัวแปร/พร็อพเพอร์ตี (public, protected, private)
- Methods - ฟังก์ชันภายในคลาส
ตัวอย่างการสร้าง Class
<?php
class myclass {
const MYCONSTANT = 100;
public $var1 = "Hello";
function dispvar() {
echo $this->var1;
}
}
?>
Function ภายในคลาสเรียกว่า Method Context ของออบเจ็กต์ที่เรียกใช้งานเข้าถึงได้ผ่าน $this (Pseudo-variable) ถ้า Method เป็น Static เรียกผ่านชื่อคลาส การเรียก Non-static Method แบบ Static ถูก Deprecated ใน PHP 7
การสร้าง Object (Instantiation)
ใช้ Operator new ตามด้วยชื่อคลาสและ Parentheses:
- ไม่มี Arguments - สร้างออบเจ็กต์ Uninitialized (หรือ Default Values)
- มี Arguments - ต้องตรงกับ Constructor Parameters
- Class ต้องถูก Define ก่อน Instantiate
<?php
class myclass {
const MYCONSTANT = 100;
public $var1 = "Hello";
function dispvar() {
echo $this->var1;
}
}
$obj = new myclass();
$obj->dispvar();
?>
ผลลัพธ์
Hello
Visibility (Access Modifiers)
| Modifier | เข้าถึงได้จาก |
|---|---|
| public | ทุกที่ (ภายใน/นอกคลาส, Child Class) |
| protected | ภายในคลาสและ Child Class เท่านั้น |
| private | ภายในคลาสที่ประกาศเท่านั้น |
Static Members
- Static Properties - เก็บค่าร่วมกันทุก Instance เรียกด้วย
ClassName::$property - Static Methods - เรียกไม่ต้องสร้าง Instance ใช้
ClassName::method()ภายในใช้self::หรือstatic::
ตัวอย่าง Static
<?php
class Counter {
public static $count = 0;
public function __construct() {
self::$count++;
}
public static function getCount() {
return self::$count;
}
}
new Counter();
new Counter();
new Counter();
echo Counter::getCount(); // 3
?>
Type Declarations (PHP 7+)
รองรับ Type Hints สำหรับ Parameters และ Return Types:
<?php
class User {
private string $name;
private int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function getName(): string {
return $this->name;
}
}
?>