物件导向程式设计 (OOP), 相信对许许多多的程式设计员都不感陌生吧 !
记得刚接触OOP时 , 常有同样的一个问题:
OOP的写法与平时写程式的方法有什么差别 ? OOP所能达到的功能, 平时用函数的写法不也能达到吗 ? 何必费时费力学呢 ?
后来才慢慢发觉, 学OOP不是费时, 而是为了节省往后写程式的时间 :) 以下就是一个简单的例子, 可以看
到, 对于"使用者"而言, 只要懂得使用
$calc = new math();
$calc->add();
$calc->set_x (1);
$calc->set_y(2);
echo $calc->calculate();
unset ( $calc );
等, 就行了, 不需要了解里面是怎样执行的, 就好象我们看电视, 并不需要了解电视的构造一样.
<html>
<head>
<title>物件导向程式设计</title>
</head>
<body>
<?
/* class 取名为 math
当然, 我们也可把这整个class"移"至另一个file, 如math.php,
必要时, 用 include("math.php") 即可 */
class math {
var $int_x; /* x 值 */
var $int_y; /* y 值 */
var $str_access_status; /* 处于什么状态: 加减乘除四种 */
function math() {
$this->_initialize(); /* 设置x值及y值的初始值 */
} //-- end math()
function _initialize() {
$this->int_x = 0; /* 初始值设为0 */
$this->int_y = 0; /* 初始值设为0 */
$this->str_access_status = ""; /* 状态设为null */
} //-- end _initialize()
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" ) {
return ($this->int_x + $this->int_y);
} elseif ( $this->str_access_status == "S" ) {
return ($this->int_x - $this->int_y);
} elseif ( $this->str_access_status == "M" ) {
return ($this->int_x * $this->int_y);
} elseif ( $this->str_access_status == "D") {
return ($this->int_x / $this->int_y);
}
}
function set_x ( $arg_x ) { $this->int_x = $arg_x; }
function set_y ( $arg_y ) { $this->int_y = $arg_y; }
} //-- end class math
/* 加法 */
$calc = new math();
$calc->add();
$calc->set_x (1);
$calc->set_y(2);
echo $calc->calculate();
unset ( $calc );
/* 减法 */
$calc = new math();
$calc->subtract();
$calc->set_x (1);
$calc->set_y(2);
echo $calc->calculate();
unset ( $calc );
/* 乘法 */
$calc = new math();
$calc->multiply();
$calc->set_x (1);
$calc->set_y(2);
echo $calc->calculate();
unset ( $calc );
/* 除法 */
$calc = new math();
$calc->divide();
$calc->set_x (1);
$calc->set_y(2);
echo $calc->calculate();
unset ( $calc );
?>
</body>
</html>
当然, 这只是一个非常简单的例子, 但别小看OOP喔. 大家都知道PHP对于每一种DB都有不同的接口吧 ! 使用OOP的方式, 我们可将之统一呢 !
|