源碼地址:https://github.com/wilfordw/phpTutorial
該系列我只寫我的理解,非官方解釋,如不夠專業請見諒
PHAR: 即 PHP Archive,將這個應用程序打包成單個文件,以利于分發和安裝的機制,似乎是從JAVA的JAR借鑒來的東西
開啟phar功能
配置php.ini
[Phar]
; http://php.net/phar.readonly
phar.readonly = Off//默認是On
基本語法
- 打包
new Phar(包名)
$phar->buildFromDirectory(打包目錄, 正則篩選);
$phar->compressFiles( Phar::GZ |PHAR::BZ2);//壓縮方式
$phar->setStub( $phar->createDefaultStub(入口文件) );
- 引用
require_once 'phar:://包名/文件';
Example
- 目錄結構
- 代碼
//user.class.php
<?php
class user {
private $name="anonymous";
private $email="anonymous@nonexists.com";
public function set_email($email) {
$this->email=$email;
}
public function set_name($name) {
$this->name=$name;
}
public function introduce() {
echo "My name is $this->name and my email address is $this->email.\n";
}
}
//user.func.php
<?php
require_once "user.class.php";
function make_user($name,$email) {
$u=new user();
$u->set_name($name);
$u->set_email($email);
return $u;
}
function dump_user($u) {
$u->introduce();
}
//test.php
<?php
require_once "user.class.php";
$u=new user();
$u->set_name("laomeng");
$u->set_email("laomeng@163.com");
$u->introduce();
通過make_phar.php打包成phar
命令行執行php make_phar.php
在目錄下就會生成user.phar
//make_phar.php
<?php
$phar = new Phar('user.phar');#定義壓縮包名
//指定壓縮的目錄,第二個參數可通過正則來制定壓縮文件的擴展名
$phar->buildFromDirectory(dirname(__FILE__) . '/user', '/\.php$/');
$phar->setStub($phar->createDefaultStub('test.php'));//設置啟動加載的文件
$phar->compressFiles(Phar::GZ);#表示使用gzip來壓縮此文件。也支持bz2壓縮。參數修改為 PHAR::BZ2即可
測試代碼
//test_phar.php
<?php
require_once "user.phar";//加載壓縮包
#My name is laomeng and my email address is laomeng@163.com.來自入口test.php
require_once "phar://user.phar/user.class.php";//加載壓縮包內php文件
$u=new user();
$u->set_name("mengguang");
$u->set_email("mengguang@gmail.com");
$u->introduce();#My name is mengguang and my email address is mengguang@gmail.com.
require_once "phar://user.phar/user.func.php";
$u=make_user("xiaomeng","xiaomeng@163.com");
dump_user($u);#My name is xiaomeng and my email address is xiaomeng@163.com.
命令行執行php test_phar.php
輸出
My name is laomeng and my email address is laomeng@163.com.
My name is mengguang and my email address is mengguang@gmail.com.
My name is xiaomeng and my email address is xiaomeng@163.com.
如此就介紹完了phar的簡單用法,個人感覺相對要比打jar包要復雜,不過引用要比jar包簡單的多,可能功能上有些缺失,不過掌握以上的功能已經夠用了