PHP شیءگرا
·
۱۰ دقیقه مطالعه
کلاس، شیء، سازنده و سطوح دسترسی
کلاس و شیء
<?php
class Account {
public string $name;
private int $xp = 0; // خصوصی
public function __construct(string $name) {
$this->name = $name;
}
public function addXp(int $amount): void {
if ($amount < 0) throw new InvalidArgumentException("منفی ممنوع");
$this->xp += $amount;
}
public function level(): int {
return intdiv($this->xp, 100) + 1;
}
}
$acc = new Account("آرنا");
$acc->addXp(250);
echo $acc->level(); // 3
__constructسازنده (هنگامnew)،$thisخودِ شیء.
سطوح دسترسی (کپسولهسازی)
public // همهجا
protected // این کلاس و فرزندان
private // فقط همین کلاس
با private داده را پنهان و از راه متدهای کنترلشده تغییر میدهی — منطق (مثل «XP منفی ممنوع») در یک جا متمرکز میشود.
Constructor Promotion (PHP 8)
class Course {
public function __construct(
public string $title,
public int $lessons = 0,
) {}
}
کوتاه و تمیز — propertyها خودکار ساخته میشوند.