(資料圖)
public訪問控制是最常用的一種,它表示對象屬性和方法可以在任何地方訪問,包括類的外部。例如:
phpCopy codeclass Person { public $name; public function greet() { echo "Hello, my name is " . $this->name; }}$person = new Person();$person->name = "John";$person->greet(); // 輸出 "Hello, my name is John"
在上面的示例中,$name屬性和greet()方法都被聲明為public,因此可以從類的外部訪問。在創(chuàng)建新的Person對象后,可以使用$person->name屬性設(shè)置$name屬性的值,并調(diào)用$person->greet()方法輸出相應(yīng)的消息。
private訪問控制表示對象屬性和方法只能在類內(nèi)部訪問。這意味著,在類的外部無法直接訪問或修改私有屬性或方法。例如:
class Person { private $name; public function setName($name) { $this->name = $name; } public function greet() { echo "Hello, my name is " . $this->name; }}$person = new Person();$person->setName("John"); // 正確$person->greet(); // 報錯,因為$name是私有屬性,無法從外部訪問
在上面的示例中,$name屬性被聲明為private,因此無法從類的外部直接訪問。相反,可以通過一個名為setName()的public方法來設(shè)置$name屬性的值,并通過$person->greet()方法輸出相應(yīng)的消息。
protected訪問控制表示對象屬性和方法只能在類內(nèi)部和其子類中訪問。這意味著,類的外部無法直接訪問或修改受保護的屬性或方法。例如:
class Person { protected $name; public function setName($name) { $this->name = $name; }}class Employee extends Person { public function greet() { echo "Hello, my name is " . $this->name; }}$employee = new Employee();$employee->setName("John"); // 正確$employee->greet(); // 輸出 "Hello, my name is John"
在上面的示例中,$name屬性被聲明為protected,因此無法從類的外部直接訪問。相反,可以通過一個名為setName()的public方法來設(shè)置$name屬性的值,并通過Employee類中的greet()方法輸出相應(yīng)的消息。由于Employee類是Person類的子類,因此可以在子類中訪問protected屬性。
責(zé)任編輯: