源码地址: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包简单的多,可能功能上有些缺失,不过掌握以上的功能已经够用了