ใน PHP5 Construct เป็นฟังก์ชั่นพิเศษ ที่จะถูกเรียกใช้งานทันทีเมื่อเราสร้างอ๊อบเจ็คจากคลาส
รูปแบบการเขียน
class Human
{
function __construct()
{
echo "My name is Bookneo";
}
}
เรียกใช้งาน$name = new Human();อีกวิธีหนึ่งก็คือ การสร้าง function ที่มีชื่อเดียวกันกับ class ตัวอย่าง
class Human
{
function human()
{
echo "My name is Bookneo";
}
}
เรียกใช้งาน
$name = new Human();ทีนี้ผมจะสร้าง file ขึ้นมา 2 ไฟล์ คือ
Myclass.php เพื่อเก็บ function ต่างๆ
myview.php สำหรับเรียกใช้งาน function หรือเป็น html page สำหรับแสดงข้อมูลออกทางจอภาพ
ไฟล์ Myclass.php ผมจะเขียนโค้ดแบบนี้
<?php
class Human
{
function __construct()
{
echo "<font color='blue'><h2>My name is Bookneo</h2></font>";
}
}
?>
ไฟล์ myview.php
<html>
<head>
<title></title>
</head>
<body>
<?php
require_once('Myclass.php');//นำเข้าไฟล์ Myclass.php
$name = new Human();
?>
</body>
</html>