简单来说,Phar就是把Java界的jar概念移植到了php界。

首先确认一下自己是否安装了phar扩展, 在php.ini里面设置 phar.readonly Off

Phar

Phar: PHP Archive support   enabled
Phar EXT version    2.0.2
Phar API version    1.1.1
SVN revision    $Id: 14b80e175ed4d5bf11c890e1f30ea8225935b16c $
Phar-based phar archives    enabled
Tar-based phar archives enabled
ZIP-based phar archives enabled
gzip compression    enabled
bzip2 compression   enabled
OpenSSL support disabled (install ext/openssl)
Phar based on pear/PHP_Archive, original concept by Davey Shafik.
Phar fully realized by Gregory Beaver and Marcus Boerger.
Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle.
Directive   Local Value Master Value
phar.cache_list no value    no value
phar.readonly   Off Off
phar.require_hash   On  On

Phar可以将一组PHP文件进行打包,还可以创建默认执行的stub(或者叫做 bootstrap loader),Phar可以选择是否进行压缩,可选gzip和bzip2格式。
下面举例说明如何创建和使用Phar:
假设我们的项目名称是user,包含三个文件:
user/user.class.php

<?php
 
class user {
    private $name="siddim";
    private $email="siddim@siddim.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/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();
}

user/test.php

<?php
require_once "user.class.php";
 
$u=new user();
$u->set_name("laomeng");
$u->set_email("laomeng@163.com");
$u->introduce();

然后我们使用如下PHP程序创建Phar文件:
make_phar.php

<?php
$phar = new Phar('user.phar', 0, 'user.phar');
$phar->buildFromDirectory(dirname(__FILE__) . '/user');
$phar->setStub($phar->createDefaultStub('test.php', 'test.php'));
$phar->compressFiles(Phar::GZ);

执行 php make_phar.php后,可以在当前目录发现一个叫做user.phar的文件。
我们可以直接执行user.phar文件:
php user.phar,这个相当于执行user/test.php
我们还可以引用此文件:
test_phar.php

<?php
require_once "user.phar";
require_once "phar://user.phar/user.class.php";
$u=new user();
$u->set_name("siddim");
$u->set_email("siddim@siddim.com");
$u->introduce();
 
require_once "phar://user.phar/user.func.php";
 
$u=make_user("siddim","siddim@siddim.com");
dump_user($u);