物件导向程式设计, 也被称为面向对像 (Object Oriented Programming, 简称OOP), 可以肯定的是它大大的提高了我们编程的效率, 更节省了我们许多宝贵的时间 ! 这里就讲解一些运用OOP时所必需知道的一些道理及步骤 :)
(一)
首先, 必需知道使用物件导向程式设计(OOP)的编程方式, 并不像平时那样, 由上至下, 而是由下至上 ! 也许有人问: 怎么说呢 ? 就拿<<物件导向程式设计>>里的一个例子好了:
一开始必需记着, 我们并不是先写它的class, 而是写它的用法
$calc = new math();
$calc->add(); //-- 告诉程式, 这是加法
$calc->set_x ($x); //-- 可以设$x的值为1
$calc->set_y($y); //-- 可以设$y的值为2
echo $calc->calculate(); //--做运算, 并将成果echo出来
unset ( $calc );
前面提过, 当一个使用者使用以上的用法时, 并没有必要知道, 用法背后是怎样执行的, 正如我们看电视一样, 不需要知道电视的构造, 用一个软件, 并不需要知道怎样制造那个软件, 只要懂得用就行了. 正因为如此, 我们使用OOP编程方式来编程时, 应做得尽善尽美, 应做到它可以独立, 而不需要靠别人的源码来支持, 就好像<<物件导向程式设计>>里的math那样, 并不需要别人的源码来支持 !
(二)
计划了用法之后, 就要开始写它的class了. 可以看到, 一开始我们就用$calc = new math(), 理所当然的, 它的class命名为math:
class math {
}
(三)
设定初始值, 可以看到, 在上面的用法当中, 可以设定初始值的只有$x及$y:
class math {
var $x;
var $y;
function math() {
$this->initialize(); //-- 设定初始值的function, 当然也可以不用
}
function initialize() {
$this->x = 0; //-- 设$x的初始值为0
$this->y = 0; //-- 设$y的初始值为0
}
}
(四)
相信各位都看到add(), 当然它也可以有subtract(), multiply()及divide(), 要怎样使程式知道那是处于什么状态呢 ? 或加, 或减, 或乘, 或除四种可能性, 所以我们另外设定一个变数特别存它的状态:
class math {
var $x;
var $y;
var $str_access_status; //--存状态的变数
function math() {
$this->initialize(); //-- 设定初始值的function, 当然也可以不用
}
function initialize() {
$this->x = 0; //-- 设$x的初始值为0
$this->y = 0; //-- 设$y的初始值为0
$this->str_access_status = ""; //-- 'A'为加, 'S'为减, 'M'为乘, 'D'为除
}
}
(五)
接下来, 就要着重于它的function了, 由上面(用法)可以看到, 它总共有几种函数: add() (当然还有其他的如subtract(), multiply()及divide()), set_x(), set_y()及calculate(), 我们全将之放进程式里:
class math {
var $x;
var $y;
var $str_access_status; //--存状态的变数
function math() {
$this->initialize(); //-- 设定初始值的function, 当然也可以不用
}
function initialize() {
$this->x = 0; //-- 设$x的初始值为0
$this->y = 0; //-- 设$y的初始值为0
$this->str_access_status = ""; //-- 'A'为加, 'S'为减, 'M'为乘, 'D'为除
}
function add() {
$this->str_access_status = "A"; //-- A代表加法
}
function subtract() {
$this->str_access_status = "S"; //-- S代表减法
}
function multiply() {
$this->str_access_status = "M"; //-- M代表乘法
}
function divide() {
$this->str_access_status = "D"; //-- D代表除法
}
/* 所有运算工作, 都在这里 */
function calculate() {
if ($this->str_access_status == "A") //-- 如果是A, 就做加法
return ($this->x + $this->y);
elseif ($this->str_access_status == "S") //-- 如果是B, 就做减法
return ($this->x - $this->y);
elseif ($this->str_access_status == "M") //-- 如果是M, 就做乘法
return ($this->x * $this->y);
elseif ($this->str_access_status == "D") //-- 如果是D, 就做除法
return ($this->x / $this->y);
}
function set_x ($arg_set_x) { $this->x = $arg_set_x; } //-- $arg_set_x所得的值全指向变数x
function set_y ($arg_set_y) { $this->y = $arg_set_y; } //-- $arg_set_y所得的值全指向变数y
}
(六)
最后, 我们将其用法摆在class之下, 只要将add(), 改为subtract(), 就可以做减法, 改为multiply(), 就可以做乘法, 改为divide(), 就可以做除法了 !
当然, 为了整个程式的"清洁", 通常class都是放在另一个档案里的, 如math.php里, 必要时, 只要用include("math.php"), 就可以"叫"它出来并使用它了 !
|