Web Development
PHP: Static
Static ใน PHP ก็เป็นอีกหนึ่ง feature ที่นอกจากประโยชน์ของมันที่ทำให้เราสามารถเข้าถึง property หรือ method ตรงๆ ได้แล้ว มันยังทำให้ code ของเราดูสวยขึ้นมากๆ
07 มกราคม 2023 • 1 นาที
0

Table of Contents
Static in class
Static ก็คือการกำหนดให้ property หรือ method ให้กับ class นั้น ๆ และสามารถเรียกใช้ได้โดยไม่ต้องสร้าง object ของ class นั้น ๆ ก่อน

class Counter {
protected static $count = 0;
public static function increment() {
static::$count++;
}
public static function decrement() {
static::$count--;
}
public static function getCount() {
return static::$count;
}
}
How to use static

Counter::increment();
Counter::increment();
Counter::decrement();
echo "Count: " . Counter::getCount(); // 1
self & static
ใน method เราสามารถใช้ self แทน static ได้ และผลลัพธ์ที่ได้ ก็จะได้เหมือนกัน

class Counter {
protected static $count = 0;
public static function increment() {
self::$count++;
}
public static function decrement() {
self::$count--;
}
public static function getCount() {
return self::$count;
}
}
Tags:PHP
คลิกเพื่อแสดงความคิดเห็น