
我們將 Encrypt 類別 (class) 取出來,放到專屬的 encryptor.php 檔案中
<?php
class Encrypt {
public $cArray = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
public $oArray = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
function __construct() {
shuffle($this->cArray);
}
function toEncode($s) {
$r = Array();
$pattern = "/[a-z]/";
for ($i = 0; $i < strlen($s); $i++) {
if (preg_match($pattern, $s[$i])) {
for ($j = 0; $j < 26; $j++) {
if ($s[$i] == $this->oArray[$j]) {
array_push($r, $this->cArray[$j]);
break;
}
}
}
else {
array_push($r, $s[$i]);
}
}
return join($r);
}
public function toDecode($s) {
$r = Array();
$pattern = "/[a-z]/";
for ($i = 0; $i < strlen($s); $i++) {
if (preg_match($pattern, $s[$i])) {
for ($j = 0; $j < 26; $j++) {
if ($s[$i] == $this->cArray[$j]) {
array_push($r, $this->oArray[$j]);
break;
}
}
}
else {
array_push($r, $s[$i]);
}
}
return join($r);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:encryptor.php
功能:示範 PHP 程式
作者:張凱慶
時間:西元 2012 年 11 月 */
?>然後 encryptdemo4.php 可以刪掉 Encrypt 類別的部份,另外在開頭加入 include()
<?php
include("encryptor.php");
echo "<br / >";
$e = new Encrypt;
echo "code: ";
for ($i = 0; $i < 26; $i++) {
echo $e->cArray[$i];
}
echo "<br / >";
$input = "There is no spoon.";
echo "input : ".$input."<br / >";
$r1 = $e->toEncode("There is no spoon.");
echo "encode: ".$r1."<br / >";
$r2 = $e->toDecode($r1);
echo "decode: ".$r2."<br / >";
echo "<br / ><br / >";
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:encryptdemo5.php
功能:示範 PHP 程式
作者:張凱慶
時間:西元 2012 年 11 月 */
?>結果會是一樣的

通常這麼做是要將函數、類別的定義放到其他檔案,這種組織程式碼的的方式對大型程式是頗有幫助的,尤其是主程式的部份不會過於凌亂。
好了,我們一直用 PHP 程式輸出結果,現在我們要把 PHP 嵌入 HTML 語法中囉!
| 中英文術語對照 | |
|---|---|
| 函數 | function |
| 類別 | class |
您可以繼續參考
網站篇
相關目錄
回 PHP 入門指南
回 PHP 教材
回首頁
參考資料
http://php.net/manual/en/language.oop5.php
http://www.php.net/manual/en/oop5.intro.php
http://www.php.net/manual/en/language.oop5.basic.php
http://php.net/manual/en/function.include.php
沒有留言:
張貼留言