OOP 中的公共、私有和受保护访问修饰符之间的主要区别是什么?
在面向对象编程(OOP)中,访问修饰符决定了类的属性和方法的可见性和访问权限。PHP 提供了 公共(public)、私有(private) 和 受保护(protected) 三种访问修饰符。以下是它们的主要区别和用法:
class Example {
public $name = "John";
public function sayHello() {
return "Hello, " . $this->name;
}
}
$example = new Example();
echo $example->name; // 输出 "John"
echo $example->sayHello(); // 输出 "Hello, John"
class Example {
private $secret = "This is private";
private function getSecret() {
return $this->secret;
}
public function showSecret() {
return $this->getSecret(); // 内部方法访问私有属性
}
}
$example = new Example();
// echo $example->secret; // 错误:无法从外部访问私有属性
// echo $example->getSecret(); // 错误:无法从外部访问私有方法
echo $example->showSecret(); // 输出 "This is private"
class ParentClass {
protected $protectedData = "This is protected";
protected function getProtectedData() {
return $this->protectedData;
}
}
class ChildClass extends ParentClass {
public function showData() {
return $this->getProtectedData(); // 子类可以访问受保护的属性和方法
}
}
$child = new ChildClass();
// echo $child->protectedData; // 错误:无法从外部访问受保护属性
echo $child->showData(); // 输出 "This is protected"
| 修饰符 | 类内访问 | 子类访问 | 类外访问 |
|---|---|---|---|
| public | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ❌ |
| private | ✅ | ❌ | ❌ |
| 修饰符 | 适用场景 |
|---|---|
| public | 需要提供给外部的功能,如类的接口或公共数据访问(例如:用户数据、公开的操作方法)。 |
| protected | 允许子类访问的功能或数据(例如:在子类中复用的通用方法或属性)。 |
| private | 仅供类内部使用的敏感数据或逻辑(例如:内部状态管理、辅助方法)。 |
class BankAccount {
private $balance; // 私有:外部无法直接访问
public function __construct($initialDeposit) {
$this->balance = $initialDeposit;
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount; // 类内部修改私有属性
}
}
public function getBalance() {
return $this->balance; // 提供公共方法访问私有属性
}
}
$account = new BankAccount(100);
$account->deposit(50);
echo $account->getBalance(); // 输出 150
// echo $account->balance; // 错误:无法直接访问私有属性
2025 年陆剧市场依旧热度爆棚
时间:2025-09-19
阵地央一首播:年度高品质大剧,深度解锁文化抗战三重非凡意义
时间:2025-09-18
陈展鹏刘佩玥《巨塔之后》今首播
时间:2025-08-28
生万物大结局惊现最招恨角色,原来真正的坏都披着善的“羊皮”!
时间:2025-08-28
归队6集燃爆:袁姗姗化身“战地玫瑰”,实战军医双在线超吸睛!
时间:2025-08-28
许凯田曦薇新剧《子夜归》首播,点击率位列第七
时间:2025-08-21