1. 程式人生 > >PHP學習 Object Oriented 面向對象 OO

PHP學習 Object Oriented 面向對象 OO

() null new extends UNC 使用 父類 object ati

定義類
class class_name [extends partclass_name]
{
public private protected var property_name = value;
public private protected function method_name (){}
}

創建對象
$Obj = new Employee();

//使用->訪問對象成員
$Obj->Name = ‘Flower‘;
$Obj->ShowName();

Static 關鍵字 純粹一般用途
class MyMath
{
public static function Cubic($x)
{
return $x*$x;
}
}

訪問
echo MyMath::Cubic(‘5‘);

類常數const

class Circle
{
const PI=3.14
public $Radius;

public function ShowArea()
{
echo $this->Radius*self::PI;
}

$Obj = new Circle();
$Obj->Radius = 10;
$Obj->ShowArea();
}

構造函數和析構函數
function _construct($str){$this->Name = $str;}

function _destruct(){$this->Name = NULL}

//PHP7 匿名類
$Obj = new class(‘小紅豆‘)
{
public $Name;
function _construct($){$this->Name = $str;}
}

繼承 extends關鍵字
覆蓋 override
調用父類 parent::
方法前加final 表示子類不能覆蓋子類成員

namespace \
namespace my\name
use my\name as MN;//命名空間別名

PHP學習 Object Oriented 面向對象 OO