phar包创建与使用

2017/06/07 php

php的版本要大于 5.3

修改php.ini

在php.ini中phar.readonly默认是开启的,将它设为 Off。(若没有则新增)

phar.readonly = Off

创建phar包

先创建以下文件

#source/mail.class.php
class Mail{
	public function send($user_address){
		echo "send {$user_address}\n";
	}
}
#source/user.class.php
class User{
	public function getAddress(){
		return 'xxxx@163.com';
	}
}
#action.php
include 'mail.class.php';
include 'user.class.php';
$User    = new User();
$address = $User->getAddress();
$Mail = new Mail();
$Mail->send($address);

执行action.php看看结果

[root@0e209db9fd6c phar_test]# php source/action.php
send xxxx@163.com

在根目录创建make.php文件,用于制作phar

$phar = new Phar('mail.phar');
$phar->buildFromDirectory(dirname(__FILE__) . '/source');
$phar->compressFiles(Phar::GZ);
$phar->stopBuffering();
$phar->setStub($phar->createDefaultStub('action.php'));

运行make.php会在目录下生成mail.phar文件

[root@0e209db9fd6c phar_test]# php make.php
[root@0e209db9fd6c phar_test]# ls
mail.phar  make.php  source

phar使用

直接运行mail.phar文件

[root@0e209db9fd6c phar_test]# php mail.phar
send xxxx@163.com

Include 文件,action.php不执行代码

include 'mail.phar';
$User    = new User();
$address = $User->getAddress();
$Mail = new Mail();
$Mail->send($address);

Include内部文件,action.php内不进行include

include 'mail.phar';
include 'mail.phar/mail.class.php';
include 'mail.phar/user.class.php';
$User    = new User();
$address = $User->getAddress();
$Mail = new Mail();
$Mail->send($address);

Search

    Table of Contents