高見龍

iOS app/Ruby/Rails Developer & Instructor, 喜愛非主流的新玩具 :)

PHP OOP

最近拿PHP來玩OOP(Object-Oriented Programming),發現這還挺有趣的 :)

建立類別

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
class myFirstClass
{
  var $username;
  var $age;

  function myFirstClass()
  {
    //this is CONSTRUCTOR!!
  }

  function showMe()
  {
    echo "My Name is " .$this->username .", and I'm " .$this->age ." years old!";
  }
}

類別實體化

1
2
3
4
5
<?php
  $myInstance = new myFirstClass();
  $myInstance->username = "eddie";
  $myInstance->age = 20;
  $myInstance->showMe();

它應該在頁面上會輸出:

My Name is eddie, and I’m 20 years old!

我用的是php4的版本,所以跟5的版本應該會有些不同,至少Contrustor的方法就不太一樣了

參考資料:

Comments