Static ও Constant

লেসন ৭ / ৩৯

Static কী?

Static property/method class-এর সাথে যুক্ত, কোনো নির্দিষ্ট object-এর সাথে নয়। Object তৈরি ছাড়াই ব্যবহার করা যায়।

Static Property

class Counter {
    public static $count = 0;

    public function __construct() {
        self::$count++;    // class-এর static property
    }
}

new Counter();
new Counter();
new Counter();

echo Counter::$count;   // 3 (object তৈরি ছাড়াই access)

Static Method

class MathHelper {
    public static function square($x) {
        return $x * $x;
    }

    public static function cube($x) {
        return $x ** 3;
    }

    public static function max($a, $b) {
        return $a > $b ? $a : $b;
    }
}

// Object তৈরি ছাড়াই কল
echo MathHelper::square(5);   // 25
echo MathHelper::cube(3);     // 27
echo MathHelper::max(10, 20); // 20

self vs $this vs static

class Demo {
    public $name;              // instance property
    public static $count = 0;  // static property

    public function instanceMethod() {
        echo $this->name;      // $this → instance
        echo self::$count;      // self:: → static
    }

    public static function staticMethod() {
        // $this ❌ — static-এ নেই
        echo self::$count;     // ✅
    }
}

Late Static Binding (static::)

class ParentClass {
    public static function create() {
        return new static();  // যে class থেকে কল, সেটারই object
    }
}

class ChildClass extends ParentClass {}

$a = ParentClass::create();  // ParentClass object
$b = ChildClass::create();    // ChildClass object ⭐

Constants (const)

Class-এ অপরিবর্তনীয় মান রাখতে const ব্যবহার হয়।

class Config {
    const VERSION = "1.0.0";
    const MAX_USERS = 1000;
    const DB_HOST = "localhost";

    public static function info() {
        echo "সংস্করণ: " . self::VERSION;
    }
}

// Access
echo Config::VERSION;       // 1.0.0
echo Config::MAX_USERS;     // 1000
Config::info();

// পরিবর্তন করা যাবে না
Config::VERSION = "2.0";    // ❌ Error

বাস্তব উদাহরণ: Database Singleton

class Database {
    private static $instance = null;
    private $conn;

    private function __construct() {
        $this->conn = new mysqli("localhost", "root", "", "mydb");
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getConnection() {
        return $this->conn;
    }
}

// সবসময় একটিই instance
$db1 = Database::getInstance();
$db2 = Database::getInstance();
// $db1 === $db2 (একই object)

Enum (PHP 8.1+)

enum Status: string {
    case Active = "active";
    case Inactive = "inactive";
    case Banned = "banned";
}

$user = new User();
$user->status = Status::Active;

echo Status::Active->value;  // "active"