標籤雲

Android (59) ActionScript (52) PHP (14) JavaScript (11) 設計模式 (10) CSS與Html (8) Flex (7) Material Design (6) frameworks (5) 工具 (5) 串流影音 (4) 通用 (4) DB (3) FlashRemoting (3) Java (3) SQL (3) Mac 操作 (2) OpenGL ES (2) PureMVC (2) React Native (2) jQuery (2) AOSP (1) Gradle (1) XML (1) 軟體設定 (1)

搜尋此網誌

顯示具有 PHP 標籤的文章。 顯示所有文章
顯示具有 PHP 標籤的文章。 顯示所有文章

2010/11/03

flash.net.registerClassAlias 與 Value Object

接續前面的內容,在 Zend_Amf 入門 裡面,透過 gateway 程式我們可以呼叫 PHP 的方法傳回資料
今天來研究一下另一種 Typed Object 的方式,把 PHP 類別 mapping 到 ActionScript 裡面(這種專門用來存放資料的物件稱為 Value Object)

首先回顧一下我們的 gateway,透過 addDirectory 我們把 AMFapp/ 下的 .php 動態載入
<?php
require_once 'Zend/Amf/Server.php';

$server = new Zend_Amf_Server();
$server->addDirectory(dirname(__FILE__) . '/AMFapp/');

$response = $server->handle();
echo $response;
?>

接下來我們在 AMFapp 下面新開一個資料夾 vo,專門用來放 Value Object 的類別
並在裡面建立一個 VOPerson.php
<?php
class VOPerson{
 //注意這裡!! 用 public $_explicitType 設定類別別名
 public $_explicitType = "VOPersonAlias";
 
 public $fName = "Joseph 喬瑟夫";
 public $lName = "Joestar 喬斯達";
 public $favoriteFood = array("T-Bone Steak", "Fried Chicken", "Chewing Gum");
 
 protected $standName = "Hermit Purple";
 private $birthday = "1920-09-27";
}
?>

除了用 public $_explicitType 設定類別別名外,也可以用 getASClassName 回傳類別別名
兩種方式擇一即可
public function getASClassName(){
 return 'VOPersonAlias';
}

有了 mapping 的 PHP 類別後,我們再寫一個 TestVO.php (放在 AMFapp下) 用來回傳這個 VOPerson 類別

<?php
//記得要把類別匯入
include 'vo/VOPerson.php';

class TestVO{
 public function getVOPerson(){
  return new VOPerson();
 }
}
?>

在 Flash 裡面我們也要準備一個跟 VOPerson 對應的類別,本例為 VOPerson.as
範例方便起見就使用 default package
package  {
 public class VOPerson {
  public var fName:String;
  public var lName:String;
  public var country:String;
  public var favoriteFood:Array;
  //非 public 的物件成員是不會 mapping 過來的,這邊只是測試用而已
  protected var standName:String;
  private var birthday:String;
  //這邊我們定義 toString 方法以便傾印資料
  public function toString():String{
   var s:String = "======== " + fName +" ‧ "+ lName +" ========\n";
   s += "國籍: "+ country +"\n";
   s += "喜歡的食物: "+ favoriteFood +"\n";
   s += "替身名: "+ standName +"\n";
   s += "生日: "+ birthday +"\n";
   s += "=================================================";
   return s;
  }
 }
}

該準備的東西都齊了,組合!!
ValueObjectTest1.fla
import flash.net.*;

//注意這裡!! 一定要註冊類別別名且與 $_explicitType 的值相同,這樣才可以正確識別
registerClassAlias("VOPersonAlias", VOPerson);

[Bindable]
var person:VOPerson;

var nc:NetConnection = new NetConnection();
var responder:Responder = new Responder(onNCResult, onNCFault);
nc.connect("http://localhost/zend_gateway.php");
nc.call("TestVO.getVOPerson", responder);

function onNCResult(re:*):void{
 person = VOPerson(re);
 trace(person); //因為我們寫了 toString(),所以可以直接 trace
}
function onNCFault(fault:Object):void{
 for(var s:String in fault){
  trace(s);
 }
}

如果順利的話就可以見到如下資訊
可以看到非 public 的屬性是過不來的
======== Joseph 喬瑟夫 ‧ Joestar 喬斯達 ========
國籍: U.S.A.
喜歡的食物: T-Bone Steak,Fried Chicken,Chewing Gum
替身名: null
生日: null
=================================================

如果出現錯誤訊息的話,請檢察類別別名是否有設定?
在 PHP 跟 AS 裡面設的別名是否相同?
需要的檔案是否正確匯入?...等

2010/11/01

ActionScript (AMF3) 與 PHP 資料型別對照表

ActionScript (AMF3) 對應 PHP 資料型別
ActionScript type (AMF3)PHP type
undefined
null
null
intinteger (超出範圍時為 float)
Number
uint
float
Booleanboolean
Stringstring
Arrayarray
XmlSimpleXml
flash.utils.ByteArraystring
Object
mx.collections.ArrayCollection
object
RemoteClass Objectclass mapped object
dateZend_Date

 

PHP 對應 ActionScript (AMF3) 資料型別
PHP typeActionScript type (AMF3)
nullnull
booleanBoolean
stringString
integer
float
Number
DomDocumentXml
DateTimeDate
Array (索引式陣列)Array
object
Array (關聯式陣列)
Object
RemoteClass Zend_Amf_Value_TypedObjecttyped object
RemoteClass Zend_Amf_Value_ArrayCollectionmx.collections.ArrayCollection

2010/10/25

Zend_Amf 入門

上一篇整理了 Flash 的資料交換方式,這次要開始慢慢切入正題
Flash Remoting 是 swf 使用 AMF 二元資料格式與伺服器的 Remoting Component 進行資料交換的技術(透過 HTTP)
在 PHP 有 amfphp, Zend_Amf 等
但由於 PHP 5.3 與 amfphp 1.9 在 localhost 測試時會出現錯誤
在找不到解決方法下,我打算改由 Zend_Amf 來上手

Zend Framework 是 Zend 公司針對 PHP 企業級開發的 Framework,而 Zend_Amf 就是其中的一組函式庫
取得的方法很簡單,只要上官方網站下載後解壓縮打開即可

而我是使用 svn 的方式來取得,既然是寫入門還是說清楚一點好了:
1. 首先如果 PC 裡沒有安裝 svn 軟體,可以下載安裝 TortoiseSVN (俗稱小烏龜)軟體
2. 在電腦裡開一個資料夾並命名,如 Zend Framework,按右鍵選擇 SVN Checkout,網址輸入 http://framework.zend.com/svn/framework/standard/trunk
3. 此時會跟網址上的檔案進行版本更新,但因為 Zend Framework 並不是很小,所以等它跑完大約需要幾分鐘

至於布署方式,只要把 library 的內容放到網站目錄下即可
(租用虛擬主機空間時由於無法更改主機設定故要用這種方式來布署)
我是選擇直接在 php.ini 裡做 include 設定,檔案就不用貼來貼去占空間
include 的方法如下:只要找到 include_path 這一行,然後以分號分隔把路徑加上去即可
路徑請記得改成自己的...

; Windows: "\path1;\path2"
include_path = ".;c:\php\includes;C:\Zend Framework\library"

這樣安裝跟布署就完成了!!

接下來還有一個重點就是要設定 Gateway 程式
在網頁目錄下新增一個 zend_gateway.php 輸入以下程式碼
並開一個子資料夾來放 remoting component,本例為 AMFapp/

<?php
//匯入 Zend/Amf/Server.php 檔案
require_once 'Zend/Amf/Server.php';

// 建立 Server 物件
$server = new Zend_Amf_Server(); //由於檔案是在 Zend/Amf/ (套件路徑)下,所以 new 的時候要寫為 Zend_Amf_Server
$server->addDirectory('AMFapp/'); //呼叫  Zend_Amf_Server 的 addDirectory 方法,將指定路徑下的檔案自動加進來

//呼叫 handle 方法處理資料並放入 $response 裡輸出
$response = $server->handle();
echo $response;
?>

而在 AMFapp 裡,開一個 HelloWorld.php 來測試吧
<?php
class HelloWorld{
 /**
  * 就是 Hello World 啦!!
  * @param string $arg
  * @return string
  */
 function sayHelloWorld($arg = ""){
  $returnValue = "Hello Zend_Amf!! 如果看到這就成功嚕!!". $arg;
  return $returnValue;
 }
}
?>

接下來是 ActionScript 的部分:(關於 NetConnection 的詳細內容請參閱官方文件)
package {
 import flash.display.*;
 import flash.net.*;
 
 public class MyTest_zend_01 extends MovieClip {
  private var ncZend:NetConnection;
  private var rsZend:Responder;
  
  public function MyTest_zend_01() {
   //建立 NetConnection 物件
   ncZend = new NetConnection();
   //將 Gateway 的完整路徑傳入 connect 方法
   ncZend.connect("http://localhost/zend_gateway.php");
   //建立 Responder 物件,指定回應與錯誤的 callback func
   rsZend = new Responder(onResult, onFault);
   //呼叫 call 方法開始連線
   //注意這裡是用 SomeClass.SomeFunc 的表示方式
   ncZend.call('HelloWorld.sayHelloWorld', rsZend, "這是傳入的字串");
  }
  //回應處理函式
  private function onResult(result:Object):void {
   trace(result);
  }
  //錯誤處理函式
  private function onFault(err:Object):void {
   trace("fault:");
   for (var i:String in err) {
    trace(i, ":", err[i]);
   }
  }
 }
}
測試發布時如果看到 output 有 trace 出訊息就表示成功了!!

2008/03/15

php-日期與時間

int time ( void )
//Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

int mktime ( [int $hour [, int $minute [, int $second [, int $month [, int $day [, int $year [, int $is_dst]]]]]]] )
//傳入時, 分, 秒, 月, 日, 年, 回傳timestamp

mixed microtime ( [bool $get_as_float] )
//回傳timestamp的毫秒與秒,傳入TRUE則回傳 Float

int strtotime ( string $time [, int $now] )
//嘗試解析的傳入字串格式的日期時間(效率很低)

array getdate ( [int $timestamp] )
//以關連式陣列回傳時間回傳

bool checkdate ( int $month, int $day, int $year )
//傳入月, 日, 年, 回傳 True or False

格式化輸出:
string date ( string $format [, int $timestamp] )
//將時間格式化輸出
例: echo date('Y-m-d H:i:s l'); //會輸出 2008-03-15 14:30:22 Saturday 這樣的格式

string strftime ( string $format [, int $timestamp] )
//可以與字串混合輸出的函式, 並可按地區設定做調整(需搭配setlocale使用)

2008/03/14

php-檔案存取

resource fopen ( string $filename, string $mode [, bool $use_include_path [, resource $context]] )
//讀取本地端或網路的檔案

mode參數如下:
r
read only;
指標在檔案開頭
r+
read, write;
指標在檔案開頭
w
write only; 覆蓋原本檔案,
若檔案不存在會嘗試建立
w+
read, write; 覆蓋原本檔案,
若檔案不存在會嘗試建立
a
write after only;
若檔案不存在會嘗試建立
a+
read & write after;
若檔案不存在會嘗試建立
x
create & write;
若檔案不存在會return False
x+
create, read & write;
若檔案不存在會return False


bool fclose ( resource $handle )
//關閉檔案

string fgets ( resource $handle [, int $length] )
//Gets a line from file pointer. 或傳入$length 指定抓取 $length - 1 bytes

string fgetc ( resource $handle )
//Gets a character from the given file pointer.

string fread ( resource $handle, int $length )
//在 $handle 中的 file pointer 位置讀取 $length bytes 的資料, 若到 EOF(end of file)也會停止

int filesize ( string $filename )
//Gets the size for the given file.

bool feof ( resource $handle )
//查看 file pointer 是否到達檔案結尾

bool file_exists ( string $filename )
//查看檔案是否存在

string file_get_contents ( string $filename [, int $flags [, resource $context [, int $offset [, int $maxlen]]]] )
//將檔案以字串型態傳回, 也可指定範圍(從 $offset 開始抓 $maxlen 長度)

int fwrite ( resource $handle, string $string [, int $length] )
//將字串從目前 file pointer 處寫入 $handle

bool fflush ( resource $handle )
//強迫將緩衝資料寫入檔案(可用來確保讀取前已經寫入)
(但會影響檔案操作速度, 故不建議平常使用)

bool is_readable ( string $filename )
//查詢是否對某檔案有讀取權限

bool is_writable ( string $filename )
//查詢是否對某檔案有寫入權限

bool unlink ( string $filename [, resource $context] )
//刪除檔案(謹慎使用...有安全性風險)

bool rename ( string $oldname, string $newname [, resource $context] )
//檔案重新命名

string basename ( string $path [, string $suffix] )
//回傳檔名

string dirname ( string $path )
//回傳檔案所在資料夾路徑

string realpath ( string $path )
//將相對路徑轉為絕對路徑

mixed pathinfo ( string $path [, int $options] )
//回傳一個檔案相關資訊的陣列

bool rmdir ( string $dirname [, resource $context] )
//刪除資料夾(注意權限)

bool mkdir ( string $pathname [, int $mode [, bool $recursive [, resource $context]]] )
//嘗試建立資料夾(注意權限)

bool chdir ( string $directory )
//改變當前工作目錄

使用函示來瀏覽目錄:
resource opendir ( string $path [, resource $context] )
//開啟目錄

string readdir ( resource $dir_handle )
//讀取目錄

void rewinddir ( resource $dir_handle )
//回到目錄開頭

void closedir ( resource $dir_handle )
//關閉目錄

使用dir類別來瀏覽目錄:
class Directory {
Directory ( string $directory )
string path
resource handle

string read ( void )
void rewind ( void )
void close ( void )
}
例:
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();

2008/03/13

php-POSIX正規表示式(regular expression)

php 相關 function:
int ereg ( string $pattern, string $string [, array &$regs] )
//Searches a string for matches to the regular expression given in pattern in a case-sensitive way.

string ereg_replace ( string $pattern, string $replacement, string $string )
//scans string for matches to pattern, then replaces the matched text with replacement.

array split ( string $pattern, string $string [, int $limit] )
//Splits a string into array by regular expression.

array explode ( string $delimiter, string $string [, int $limit] )
//比 split 快, 但不支援多位元

使用方法:
正規表示式須放在單引號中

字元類別: 用 [ ] 包圍, 方括符內的任一字元都算
連字元 [a-z]、[A-Z]、[0-9] 可連用如: [A-Za-z0-9], 若寫為[A-z]則也包含[]^_等字元, 但寫為[a-Z]則不合法, 因為 Z 的ASCII編碼在 a 前面
^字元, 表示互斥, 例: [^aeiou]表示除aeiou這五個字元之外的都算

POSIX 命名字元類別有:(需在字元類別內使用)
[:alnum:] --ASCII字母及數字, 相當於[A-Za-z0-9]
[:alpha:] --ASCII字母, 相當於[A-Za-z]
[:blank:] --空格及tab, 相當於[ \t]
[:space:] --空白字元(空格、換行、tab及垂直tab), 相當於[\n\r\t \x0b]
[:cntrl:] --不可列印的控制字元, 相當於[\x01-\x1f]
[:digit:] --相當於[0-9]
[:lower:] --相當於[a-z]
[:upper:] --相當於[A-Z]

邊界:
[:<:] --右邊界 [:>:] --左邊界
^ --字串開頭(元字元 metacharacter, 須在方括符外面使用)
$ --字串結尾(元字元, 須在方括符外面使用)

點號:
. 點號代表任一單一字元, 實際字串中的點號需用 \. 轉義
但是字元類別中的點號 . 就是代表點號

量詞:(quantifier)
{min, max} -- 出現的最小值與最大值
* --代表 {0,} 即 零或多
+ --代表 {1,} 即 一或多
? --代表 零或一 (可以不出現, 但若出現只能一次)

分組:
使用 ( ) 小括符將字串包圍, 但要注意使用分組則效能會較差, 可搭配序列分割符號 | 使用
例:
(very{1,})
(good|awesome|amazing)

反向引用: (back reference)
php的POSIX正規表示式中將分組命名為 \1, \2, ... , \n (其中 n 只能到 9)
\0 表示引用整個字串
例:
$replaced = ereg_replace('([%;])', '\\\1', $myString)
就將 $myString 中的 % 或 ; 符號替換成 \ 符號
(\\代表跳脫轉義的 \ 而後面的 \1 則是反向引用)

綜合範例:

[[:alnum:] _-]{6,30}
代表大小寫字母與數字還有空格, 底線, 橫線都接受, 最少6字元最大30字元

2008/03/10

php-Cookie 與 Session

bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [, bool $secure [, bool $httponly]]]]]] )
//設定cookie, , 該行前不能有任何空白, 否則等於有輸出
$expire 設為 0 表示為 session cookie(只存在記憶體中, 而不是硬碟中 )
$path 為 cookie 的有效範圍, 若設為"/" 表示對此網站任何目錄下的頁面都有效
$domain 該 cookie 有效的域名
$secure 設為 1 時, 表示只在 HTTPS 有效

刪除cookie:
設定已經過去的時間, cookie 就會被客戶端清掉


Session:
Session 使用 Session cookie, 並用 Session ID 跟客戶端連接起來

string session_name ( [string $name] )
//Get and/or set the current session name

bool session_start ( void )
//建立session, 若要使用有名稱的session 則需先呼叫session_name ( [string $name] )

string session_cache_limiter ( [string $cache_limiter] )
//參數說明: 'nocache' 不允許任何 client/proxy 快取; 'public' 允許快取; 'private' 不允許 proxy 但允許 client 快取; 使用時須在 session_start 呼叫前

int session_cache_expire ( [int $new_cache_expire] )
//設定/查詢快取失效期限, 回傳值為新的快取期限, 單位為分鐘, 預設為 180 (即 3 小時)

刪除 session: 三步驟:
一)
bool session_destroy ( void )
//Destroys all data registered to a session
二)
setcookie(session_name(), '', time()-3600)
//將客戶端的session cookie刪除,
三)
$_SESSION = array();
//清空super global的 $_SESSION 陣列

session 儲存:
bool session_set_save_handler ( callback $open, callback $close, callback $read, callback $write, callback $destroy, callback $gc )

2008/03/09

php-物件導向 mysqli

連線:
class mysqli {
__construct ( [string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket]]]]]] )}
//Open a new connection to the MySQL server

int mysqli_connect_errno ( void )
//Returns the last error code number from the last call to mysqli_connect()

string mysqli_connect_error ( void )
//Returns the last error message string from the last call to mysqli_connect().

檢索:
class mysqli {
mixed query ( string $query [, int $resultmode] )
}
//Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

class mysqli_result {
array fetch_assoc ( void )
}
//以關聯式陣列形式傳回, 因此重複的列名只有最後一筆會包含, 當無下一筆時傳回 NULL

class mysqli_result {
mixed fetch_array ( [int $resulttype] )
}
//傳回以數字為索引的陣列(不用擔心列名重複), 當無下一筆時傳回 NULL

轉義以過濾輸入值(防止 injection attack):
class mysqli {
string escape_string ( string $escapestr )
string real_escape_string ( string $escapestr )
}
//過濾傳入的字串, 轉義以下特殊符號 NUL (ASCII 0), \n, \r, \, ', ", Control-Z

交易處理(transaction):
class mysqli {
bool autocommit ( bool $mode ) //開啟或關閉自動提交, 建議關閉
bool commit ( void )
bool rollback ( void )
}

預備敘述( Prepared Statements ):
class mysqli {
mysqli_stmt prepare ( string $query )
}
//產生 mysqli_stmt 物件, $query 中欄位參數的值應以 ? 取代

class mysqli_stmt {
bool bind_param ( string $types, mixed &$var1 [, mixed &$...] )
//綁定參數, 將值與參數名稱指定給 mysqli_stmt 物件

bool bind_result ( mixed &$var1 [, mixed &$...] )
//綁定結果(將結果綁定到 php 變數上)

bool fetch ( void )
//將綁定結果依序放入敘述中, 成功傳回 True, 失敗傳回 False, 沒有值時傳回 Null
}

2008/03/06

php基礎-伺服器變數

伺服器變數:(非全部)
$_SERVER["PHP_SELF"]
//該程式在網站根目錄中的相對路徑與檔名
$_SERVER["SERVER_NAME"]
//伺服器的網域名稱, 如 www.hostname.com
$_SERVER["SERVER_SOFTWARE"]
//伺服器執行的軟體 如: Apache/2.2.8 (Win32) PHP/5.2.5
$_SERVER["SERVER_PROTOCOL"]
//目前使用哪種通訊協定
$_SERVER["REQUEST_METHOD"]
//request的方式, 如: GET, POST...
$_SERVER["REQUEST_TIME"]
//接收到 request 的時間(非所有伺服器都可用)
$_SERVER["DOCUMENT_ROOT"] // 網站根目錄在伺服器的路徑(非所有伺服器都可用, 可用$_SERVER["ORIG_PATH_TRANSLATED"]去掉後面$_SERVER["PHP_SELF"] 的值得出相同結果)
$_SERVER["HTTT_USER_AGENT"]
//用戶的瀏覽器
$_SERVER["REMOTE_ADDR"]
//用戶的IP位置(注意: 來自相同session的用戶實際上可能來自不同IP)

環境變數:$_ENV[]

重導用戶:
void header ( string $string [, bool $replace [, int $http_response_code]] )
使用 "Location:" 來做頁面重新導向
例: header("Location: http://www.example.com/");
或是: header('Location:http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/myfilename.php';
//header()前面若有空白, php會發送輸出流, 導致 header() 錯誤

2008/03/02

php基礎-String

String 相關 function :
字串長度:
int strlen ( string $string )
//Get string length
int mb_strlen ( string $str [, string $encoding] )
//與strlen相同...但是多位元的字碼(如中文字)會被正確計算, 若要計算位元或字串的二進位長度, 第二個參數可以設為 '8bit'

字元轉換:
string chr ( int $ascii )
//Return a specific character
int ord ( string $string )
//Return ASCII value of character
string mb_detect_encoding ( string $str [, mixed $encoding_list [, bool $strict]] )
//判斷給定字串的編碼為何..對類似字元集的編碼未必準確

Unicode 轉換:
string utf8_encode ( string $data )
//Encodes an ISO-8859-1 string to UTF-8
string utf8_decode ( string $data )
//Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

字元編碼轉換:
string iconv ( string $in_charset, string $out_charset, string $str )
//把 $str 字串從 $in_charset 編碼轉為 $out_charset 編碼

字串整理:
string trim ( string $str [, string $charlist] )
//刪除字串的空白(含 tab 空白 \r\n 等), 第二個參數可指定在字串中要刪除的其他字元
string ltrim ( string $str [, string $charlist] )
//刪除字串前面的空白
string rtrim ( string $str [, string $charlist] )
//刪除字串後面的空白

字串搜尋與比較:
int strpos ( string $haystack, mixed $needle [, int $offset] )
//在 $haystack 字串裡找尋 $needle 的索引位置, 也可指定從 $offset 位置開始找, 但若第一個字元就找到(索引為0), 會被認為是找不到(False), 可以利用 === 確定
int mb_strpos ( string $haystack, string $needle [, int $offset [, string $encoding]] )
//同 strpos, 最後一個 $encoding 參數可以指定字串的編碼
int strcmp ( string $str1, string $str2 )
//比較兩字串位元組(二進位), 回傳 -1 表示 $str1 < $str2, 回傳 1 表示 $str1>$str2, 回傳 0 表示字串位元相等
int strncmp ( string $str1, string $str2, int $len )
//同 strcmp,(二進位), 第三個函數是只比較前 $len 個字元
int strcasecmp ( string $str1, string $str2 )
//不區分大小寫的strcmp
int strncasecmp ( string $str1, string $str2, int $len )
//不區分大小寫的strncmp int strnatcmp ( string $str1, string $str2 )
//對數字進行人性化比較的 strcmp
int strnatcasecmp ( string $str1, string $str2 )
//對數字進行人性化比較的 strcasecmp

擷取:
string substr ( string $string, int $start [, int $length] ) //從 $string 的 $start 索引開始擷取 $length 長度的子字串

大小寫操作:
string strtoupper ( string $string )
//轉大寫
string strtolower ( string $str )
//轉小寫
string mb_strtoupper ( string $str [, string $encoding] )
//多位元版轉大寫
string mb_strtolower ( string $str [, string $encoding] )
//多位元版轉小寫

2008/03/01

php基礎-Array

php array 的合法呼叫:
{$myArr['myKey']} //推薦寫法! key若加引號, 須加大括弧
"$myArr[myKey]" //在引號內使用時, key不加引號也可以, 但不推薦
{$myArr[MY_CONST]} //key為常數變數時, 須加大括弧

foreach 迴圈:
forrach($myArr as $key =>$value){}

相關函數:
unset($myArr); //刪除陣列或陣列元素
int count ( mixed $var [, int $mode] )
//Count elements in an array, or properties in an object
array array_keys ( array $input [, mixed $search_value [, bool $strict]] )
//將傳入陣列的所有key成為一個新的陣列傳回
bool array_walk ( array &$array, callback $funcname [, mixed $userdata] )
//Apply a user function to every member of an array
array array_fill ( int $start_index, int $num, mixed $value )
//Fill an array with values
array array_merge ( array $array1 [, array $array2 [, array $...]] )
//Merge one or more arrays
array array_combine ( array $keys, array $values )
//Creates an array by using one array for keys and another for its values, 當兩陣列長度不同時傳回False
array array_intersect ( array $array1, array $array2 [, array $ ...] )
//傳回兩個陣列中相同的值, 並以 $array1 的 key 為 key
mixed array_search ( mixed $needle, array $haystack [, bool $strict] )
//在 $haystack 陣列中找尋為 $needle 的值, 成功則傳回該值的 key

bool sort ( array &$array [, int $sort_flags] )
//為 array 中的元素重新排序(刪除原有的key, 賦予新的key)
bool asort ( array &$array [, int $sort_flags] )
//為 array 中的元素重新排序(原有的key依然保持跟值配對的狀態)
bool rsort ( array &$array [, int $sort_flags] )
//Sort an array in reverse order
bool arsort ( array &$array [, int $sort_flags] )
//Sort an array in reverse order and maintain index association
bool usort ( array &$array, callback $cmp_function )
//Sort an array by values using a user-defined comparison function
bool uasort ( array &$array, callback $cmp_function )
//Sort an array with a user-defined comparison function and maintain index association
bool ksort ( array &$array [, int $sort_flags] )
//Sort an array by key
bool krsort ( array &$array [, int $sort_flags] )
//Sort an array by key in reverse order
bool uksort ( array &$array, callback $cmp_function )
//Sort an array by keys using a user-defined comparison function

array each ( array &$array )
//取得陣列中所有key/value值配對, 常搭配迴圈使用
mixed next ( array &$array )
//陣列cursor前後移一位並回傳該值, 無法移動則傳回False, 若值就是False則易混淆
mixed prev ( array &$array )
//陣列cursor向後移一位並回傳該值, 無法移動則傳回False, 若值就是False則易混淆
mixed current ( array &$array )
//回傳陣列cursor所在位置的值, 別名 pos()
mixed reset ( array &$array )
//Set the internal pointer of an array to its first element

php基礎-php的物件導向簡要

visibility keyword: public, protected, private

建構子:
與 Java 不同, 不跟類別同名, 寫法與function 相同, 名稱為 public function __construct
另有 __destruct 於清除類別時呼叫

類別常數:
關鍵字 const , 沒有修飾子, 全大寫字母, 無 $ 標記, 宣告後唯讀
在class外使用時 類別名稱::常數名稱
在class內使用時 self::常數名稱

static:
只能是 public 並使用 :: 來存取值

function 的 overriding :
在 overriding 時調用父類別的同名函數時使用 parent::函數名(參數)

抽象類別 abstract 與介面 interface:
抽象類別關鍵字 abstract , 只能被繼承, 不能自己產生 instance, abstract function僅有名稱及參數定義, 無實作
當class內有一個 function 定義為abstract時, 該 class 必須定義為 abstract

interface 裡面的 function 全是抽象( 但省略 abstract 關鍵字 ), 且只能被實作( implements )
如果沒有完全實作 interface 裡面的 function , 則該 class 還是 abstract (不能被new)

final:
防止 function 或變數被 overriding 或繼承

複製:
$a = new MyClass();
$b = clone $a;
/*
$b 把 $a 複製了一份..即兩個不同的 MyClass 實體, 但為淺度複製, 其方式為呼叫該 class 內的 public function __clone()
因此可以自行定義該 function 進行操作
*/

__toString :
把物件實體作為唯一參數傳給 print 或 echo 時, 會呼叫該類別的 public function __toString()
可overriding 使輸出結果合乎要求

type hine:
在向 function 傳遞參數時, 若參數為物件, 可指定他必須為某類別(或其子類別)
function get_prod(MyClass $a){} //指定傳入的 $a 參數必須為 MyClass 的實體, 或其子類別

__autoload :(PHP5)
在 php 頁面中實作 function __autoload(), 將要 include或 require 的類別名稱作為參數傳入
並在 function 中對需要用到的類別作 include 或 require 呼叫
php 就會自動執行它

2008/02/26

php基礎-2

PHP Superglobals (超全域變數)
$GLOBALS
每個全域範圍內有效的變數, 該 array 的 key 為全域變數的名稱
$_SERVER
由 web server設定的變數或者直接與當前的執行環境相關聯。類似於 $HTTP_SERVER_VARS
$_GET
經由 URL query string提交的變數, 類似於 $HTTP_GET_VARS
$_POST
經由 HTTP POST 方法提交的變數, 類似於 $HTTP_POST_VARS
$_COOKIE
經由 HTTP Cookies 方法提交的變數。類似於 $HTTP_COOKIE_VARS
$_FILES
經由 HTTP POST 文件上傳而提交的變數。類似於 $HTTP_POST_FILES
$_ENV
執行環境提交的變數。類似於 $HTTP_ENV_VARS
$_REQUEST
經由 GET, POST, COOKIE 機制提交的變數, 因此並不值得信任, 所有包含在該 array 中的變數存在與否以及變數的順序均按照 php.ini 中 variables_order 的設定來定義
(運行於命令行模式時此 array 不會包含 argv 和 argc; 它們已經存在於 $_SERVER 中)
$_SESSION
註冊給session的變數, 類似於 $HTTP_SESSION_VARS

變數範圍:
global 關鍵字--在 function 中使用 global 把 function 外的變數引入, 或是用 $GLOBALS 代替global關鍵字
static 靜態變數--static 變數只在 function 中存在, 但離開function時值還在, 在 static 宣告中若將 expression asign給它會導致錯誤

可變變數:
$a='hello';
$$a = 'world';
echo "$a{$$a}"; //把$a的值當作變數名

來自 PHP 之外的變數:
HTTP表單: $_POST 跟 $_GET
HTTP cookies: 使用 setcookie() 設定 cookie, 同名會替換, 要調用則使用 $_COOKIE
(注意: 因為 . 代表字串相連, 所以php會自動將變數名中的 . 換成 _ )

include 與 require: (include_once 與 require_once)
include 跟 reruire 的主要差別在於, 當檔案找不到時, include 產生警告並繼續執行, require 則傳出fatal error 並終止程式

被包含的檔案可以使用包含它的檔案的變數, 也可return值給包含它的檔案

如果被包含的檔案裡面還有 include 或 require 其他檔案, 可以使用 include_once 和 require_once 這樣一來可以把裡面包含的檔案一次載入

2008/02/20

php基礎-1

php的資料型態:
Boolean - 轉換型別時 0, 空字串, 空變數, 空物件, NULL都轉換為False; 其餘會轉換為True
Integer - 支援10進位, 8進位,16進位
Float - 不精準, 支援Double關鍵字
String - 雙引號字串裡的變數會顯示變數值, 單引號字串則不會; 字串可用 . 連接;
支援以下跳脫字元:
\n -linefeed (LF or 0x0A (10) in ASCII)
\r -carriage return (CR or 0x0D (13) in ASCII)
\t -horizontal tab
\v -vertical tab (PHP 5.2.5)
\f -form feed(PHP 5.2.5)
\\ -backslash
\"
\'
\$
\[0-7]{1,3} -八進位
\x[0-9A-Fa-f]{1,2} -十六進位
Array - 用法 $a = array('aa', 'bb', 'cc) 或 $a[0]="aa"
或使用 key => value配對: $arr = array("foo" => "bar", 12 => true); //key為字串時須加 " " 或 ' '
$a = array(5 => 43, 32, 56, "b" => 12); //$a[6]為32, $a[7]為56
移除 array 裡的 key可使用 unset()
php支援多維陣列
Object - 物件導向
object之外的類型轉型成object, 會建立一個 stdClass, 若是NULL 則該物件也是NULL; 若是 array 則會將key與值轉換成屬性; 若是其他型別則會以 scalar
Resource - php可以透過特殊函數控制外部物件, 如資料庫連線, 開啟檔案
NULL - 三種情況下變數為NULL: 1-變數被 asign 為 NULL; 2-變數還沒有被 asign 值; 3-變數被unset()

型別轉換:
(int)、(integer)、intval() -無條件捨去
(float)、(double)、(real)、floatval()
(bool)、boolean()
(string)、strval()
(binary) - cast to binary string
(array)
(object)
object之外的類型轉型成object, 會建立一個 stdClass, 若是NULL 則該物件也是NULL; 若是 array 則會將key與值轉換成屬性; 若是其他型別則會以 scalar

php變數:
以 $ 開頭, 其後第一個字為字母(大小寫區別)或 _ (底線且後面接大寫字母的通常是php系統變數), 之後的可使用底線, 字母, 數字

常數:
bool define ( string name, mixed value [, bool case_insensitive] )
常數用 define() 定義(若已有此常數會回傳false), 常數名不以 $ 開頭, 且只能是 int, float, string, boolean

傳值與傳址:
php中的 asignment 全部是 passing value, 除非加上 & 運算子才會 passing reference
只有"有名字"的"變數"才可以用 & 做傳址 asignment
$foo = 25;
$bar = &$foo;
$bar = &(24 * 7); //這行是錯的, 另外 function 名稱也不可以傳址