最近在不得已的情況下,不得不來看PHP!雖然沒有很愛它!不過還是該來學一下
OOP(object oriented programming)在程式的的撰寫以及維護上有很好的性質,當然這些好的性質姑狗一下就有,在這裡就不多說,在這裡主要記錄關於php相關的oop觀念
1. 物件create
<?php
class Courier{
public $name;
pbulic $home_country;
public function __construct($name){
$this->name = $name;
return true;
}
public function ship($parcel){
return true;
}
}
?>
2. 實例化一個object
<?php
$ mono = new Courier('Monospace Delivery');
?>
3. static property & method
注明一下,static的property和method是被所有instances所共用,也就是說假設有obj1,obj2,...,objN,他們都有一個static變數$var,則不管obj1->var,obj2->var,...,objN->var的值都相同
<?php
class Courier{
public $name;
public $home_country;
public static function getCouriersByCountry($country){
// get home_country = $country list
// add result to an array -> courier_list
echo $country_list;
}
}
?>
使用方法(用兩個冒好::,這代表範圍解析運算子)
$spanish_couriers = Courier::getCouriersByCountry('Spain');
4. object inheritance(繼承)
class可以繼承或是擴充(extend)一個父類別(parent class),所以要繼承parent可用extends關鍵字
<?php
//Parent class
class Courier{
public $name;
public $home_country;
public function __construct($name){
$this->name = $name;
return true;
}
public function ship($parcel){
// ship package to destination
return true;
}
public function calculateShipping($parcel){
$rate = 1.78;
$cost = $rate * $parcel->weight;
return $cost;
}
}
// Child class
class MonotypeDelivery extends Courier{
public function ship($parcel){
// put items in box
// send
return true;
}
}
// Child class
class PigeonPost extends Courier{
public function ship($parcel){
// capture Messenger
// attach package
// send
return true;
}
}
?>
5. Array & Dictionary
在PHP中,不管是Array或是Dictionary都使用同一種物件Array()
<?php // create an array $array = array(); // add item to array $array[] = "item"; // Array $array[$key] = "item"; // Dictionary array_push($array, "item", "another item"); //Array // remove item from array $item = array_pop($array); $item = array_shift($array); unset($array[$key]); ?>
最後php有個很好用的function可以幫助debug-> var_dump(obj)
<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
?>
output:
array(4) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(5) "hello"
[3]=>
string(5) "world"
}
沒有留言:
張貼留言