Devdit
 

PHP function construct คืออะไร ใช้ทำอะไร

853

PHP function construct คือฟังก์ชันที่มีชื่อเป็น __construct ทำหน้าที่กำหนด properties หรือเขียนโค้ดประมวลผลให้กับ object ตอนที่สร้าง class ได้เลย โดยฟังก์ชัน __construct เป็นส่วนหนึ่งของ OOP สามารถเขียนโปรแรกมได้ดังนี้

 

ตัวอย่าง PHP function construct คืออะไร ใช้ทำอะไร

<?php
  class Plus {
    private $number1;
    private $number2;
    private $total;
    
    function __construct( $number1, $number2 ) {
      $this->number1 = $number1;
      $this->number2 = $number2;
      $this->total = $this->number1 + $this->number2;
    }
    function getTotal() {
      return $this->total;
    }
  }

  $plus = new Plus(8, 9);
  echo $plus->getTotal();
?>

ผลลัพธ์

17

คำอธิบาย

PHP function construct จากตัวอย่างสร้างฟังก์ชัน __construct พร้อมรับค่า properties 2 ตัวคือ number1 และ number2 โดยฟังก์ชัน __construct นี้จะทำหน้าที่บวกเลยระหว่าง 2 ตัวแปรดังกล่าวเก็บค่าไว้ที่ตัวแปร total เวลาสร้าง object จาก class คือ $plus = new Plus(8, 9) หมายความว่าสร้าง object ชื่อ $plus จาก class Plus พร้อมกำหนด properties คือ number1 = 8 และ number2 = 9 จากนั้นแสดงผลลัพธ์ที่เก็บไว้ในตัวแปร total ด้วย $plus->getTotal()

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ