• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

使用Phar回打包发布PHP程序

php 搞代码 3年前 (2022-01-24) 10次浏览 已收录 0个评论

使用Phar来打包发布PHP程序

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

Phar可以将一组PHP文件进行打包,还可以创建默认执行的stub(或者叫做?bootstrap loader),Phar可以选择是否进行压缩,可选gzip和bzip2格式。

下面举例说明如何创建和使用Phar:

假设我们的项目名称是user,包含三个文件:

user/user.class.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?php

?

class?user {

????private?$name="anonymous";

????private?$email="[email protected]";

?

????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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<?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

1

2

3

4

5

6

7

<?php

require_once?"user.class.php";

?

$u=new?user();

$u->set_name("laomeng");

$u->set_email("[email protected]");

$u->introduce();

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

make_phar.php

1

2

3

4

5

<?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

1

2

3

4

5

6

7

8

9

10

11

12

<?php

require_once?"user.phar";

require_once?"phar://user.phar/user.class.php";

$u=new user();

$u->set_name("mengguang");

$u->set_email("[email protected]");

$u->introduce();

?

require_once?"phar://user.phar/user.func.php";

?

$u=make_user("xiaomeng","[email protected]");

dump_user($u);

参考资料:

https://php.net/manual/en/book.phar.php


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用Phar回打包发布PHP程序
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址