Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Getter และ Setter Methods ใน PHP


Getter และ Setter Methods ใช้เมื่อต้องการจำกัดการเข้าถึง property โดยตรงจากภายนอก Getter ใช้ดึงค่า Setter ใช้ตั้งค่า มักใช้กับ property ที่เป็น private

ตัวอย่าง

<?php 
class Person{ 
    private $name; 
    public function setName($name){ 
        $this->name = $name; 
    } 
    public function getName(){ 
        return $this->name; 
    } 
} 
$person = new Person(); 
echo $person->name; 
?>

ผลลัพธ์

PHP Error Cannot access private property Person::$name

คำอธิบาย

property $name เป็น private ไม่สามารถเข้าถึงโดยตรงได้ จะเกิด fatal error

ตัวอย่างที่ถูกต้อง

<?php 
class Person{ 
    private $name; 
    public function setName($name){ 
        $this->name = $name; 
    } 
    public function getName(){ 
        return 'welcome ' . $this->name; 
    } 
} 
$person = new Person(); 
$person->setName('Alex'); 
$name = $person->getName(); 
echo $name; 
?>

ผลลัพธ์

welcome Alex

คำอธิบาย

ใช้ setter ตั้งค่า private property และ getter ดึงค่าออกมา encapsulation