Classes and Objects

🔹 Class چیست؟

یک کلاس (Class) مثل یک قالب یا نقشه است که ویژگی‌ها (Properties) و رفتارها (Methods) را تعریف می‌کند.

🔹 Object چیست؟

یک شیء (Object) نمونه‌ای (Instance) از یک کلاس است.
وقتی از یک کلاس شیء می‌سازیم، می‌توانیم از ویژگی‌ها و متدهای آن استفاده کنیم.

🔹 تعریف یک کلاس

<?php class Car { // Property (ویژگی‌ها) public $color; public $brand; // Method (رفتارها) function setBrand($brand) { $this->brand = $brand; } function getBrand() { return $this->brand; } } ?>

🔹 ساخت یک Object

<?php $car1 = new Car(); // شیء اول $car1->setBrand("BMW"); $car2 = new Car(); // شیء دوم $car2->setBrand("Toyota"); echo $car1->getBrand(); // خروجی: BMW echo "<br>"; echo $car2->getBrand(); // خروجی: Toyota ?>

📌 در اینجا از یک کلاس، دو شیء مختلف ساخته‌ایم.

🔹 استفاده از this->

کلمه‌ی کلیدی $this برای اشاره به شیء جاری استفاده می‌شود.
یعنی وقتی داخل کلاس هستیم و می‌خواهیم به ویژگی یا متد شیء دسترسی داشته باشیم، از $this استفاده می‌کنیم.

🔹 متد __construct() (سازنده)

کلاس‌ها در PHP می‌توانند متد ویژه‌ای به نام __construct() داشته باشند که هنگام ساخت شیء به طور خودکار اجرا می‌شود.

<?php class Car { public $color; public $brand; function __construct($color, $brand) { $this->color = $color; $this->brand = $brand; } function getMessage() { return "This car is a " . $this->color . " " . $this->brand; } } $myCar = new Car("Red", "BMW"); echo $myCar->getMessage(); ?>

📌 خروجی:

This car is a Red BMW

🔹 متد __destruct() (تخریب‌گر)

این متد به صورت خودکار در پایان اجرای اسکریپت یا وقتی شیء نابود می‌شود، اجرا خواهد شد.

<?php class Car { public $brand; function __construct($brand) { $this->brand = $brand; } function __destruct() { echo "The car is a {$this->brand}."; } } $myCar = new Car("Toyota"); ?>

📌 خروجی هنگام پایان اجرای اسکریپت:

The car is a Toyota.

✅ خلاصه

  • Class = قالب یا نقشه

  • Object = نمونه‌ای از کلاس

  • $this = اشاره به شیء جاری

  • __construct() = متدی که هنگام ایجاد شیء اجرا می‌شود

  • __destruct() = متدی که هنگام پایان کار شیء اجرا می‌شود