Results 1 to 2 of 2

Thread: เขียน PHP แบบ OOP: ตอน การสร้าง Constructor ของ Class

  1. #1
    Junior Member
    Join Date
    Jul 2010
    Posts
    11


    เขียน PHP แบบ OOP: ตอน การสร้าง Constructor ของ Class

    การสร้าง Constructor ของ Class

    รายละเอียด

    //File: Human.php
    Code:
    <?php
    class Human
    {
    var $name ;
    var $height;
    var $weight;
    
    function Human($aName,$aHeight,$aWeight)  // Constructor คือ function ที่มีชื่อเดียวกับ class ทำหน้าที่ ในการกำหนดค่าเริ่มต้น
    {
    $this->name = $aName;
    $this->height = $aHeight;
    $this->weight = $aWeight;
    }
    function setName($name)
    {
    $this->name = $name;
    }
    function getName()
    {
    return $this->name;
    }
    function setHeight($height)
    {
    $this->height = $height;
    }
    function getHeight()
    {
    return $this->height;
    }
    function setWeight($weight)
    {
    $this->weight = $weight;
    }
    function getWeight()
    {
    return $this->weight;
    }
    }
    ?>
    
    // File: TestClient.php
    
    <?
    require("Human.php");
    $human = new Human("Doing",160,60);
    echo "Name: ".$human->getName();
    echo "<br>Height: ".$human->getHeight();
    echo "<br>Weight: ".$human->getWeight();
    
    ?>

    Code:
    Result
    ----------
    Name: Doing
    Height: 160
    Weight: 60
    Ref: https://sites.google.com/site/oopinphp/
    Last edited by doing; 15-08-2010 at 09:36 PM.

  2. #2
    Junior Member
    Join Date
    Mar 2008
    Location
    ดาวนาเม็ก
    Posts
    5


    ผมขอเพิ่มรายละเอียดให้.

    สำหรับ PHP การใช้ชื่อ Function เป็น Constructor ไม่ Support ในเวอร์ชั่นล่าสุดแล้วนะครับ ถ้าหากจะสร้าง Constructor จะต้องสร้างโดยการกำหนดเป็น
    function __construct() {}
    ครับ ในเวอร์ชั่นตั้งแต่ PHP 5.3.3 เป็นต้นไป มีการ Support Namespace และถ้าหากมีการใช้ Namespace ด้วย Function ที่เป็นชื่อเดียวกันกับชื่อคลาส จะจัดเป็นฟังก์ชั่นธรรมดา ไม่ได้เป็น Constructor อีกต่อไปครับ รายละเอียดอ่านเพิ่มเติมได้จากที่นี่ครับ.

    PHP: Constructors and Destructors - Manual

Similar Threads

  1. Replies: 0
    Last Post: 12-08-2010, 03:03 PM
  2. Replies: 0
    Last Post: 12-08-2010, 02:49 PM
  3. Replies: 0
    Last Post: 12-08-2010, 02:02 PM
  4. Icon Constructor 3.54
    By RavMonK in forum Window Application
    Replies: 0
    Last Post: 14-09-2007, 05:43 PM
  5. Constructor คืออะไรครับใน C++
    By Anonymous in forum C/C++,C#,VC++,MFC,Win32
    Replies: 1
    Last Post: 20-11-2004, 07:48 PM

Members who have read this thread : 0

Actions : (View-Readers)

There are no names to display.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •