【问题标题】:Include PHP PHAR without .phar extension包含没有 .phar 扩展名的 PHP PHAR
【发布时间】:2020-04-05 17:38:30
【问题描述】:

我在将 PHAR 包含到我的应用程序引导代码中时遇到了问题。我正在尝试包含 phpunit/phpunit PHAR 以在我的应用程序中提供 PHPUnit 类。

鉴于我有以下目录结构:

/path/to/code/
    app.php
    phpunit

phpunit 是作为 PHAR 的 PHPUnit,app.php 包含:

<?php

$phar = 'phar://' . __DIR__ . '/phpunit';

include $phar;

assert(class_exists('\\PHPUnit\\Framework\\TestCase'));

我收到以下错误:

PHP Warning:  include(phar:///path/to/code/phpunit): failed to open stream:
    phar error: no directory in "phar:///path/to/code/phpunit",
    must have at least phar:///path/to/code/phpunit/ for root directory
    (always use full path to a new phar) in /path/to/code/app.php on line 4

但是当我将 PHAR 重命名为 phpunit.phar 并包含它而不是使用

<?php

$phar = 'phar://' . __DIR__ . '/phpunit.phar';

include $phar;

assert(class_exists('\\PHPUnit\\Framework\\TestCase'));

代码运行良好,TestCase 类存在。

为什么第一个版本不起作用,关于“新 phar 的完整路径”的错误是什么意思?


我的 PHP 版本是 7.2,而 PHPUnit PHAR 是 7.* 版本,它已与 Phive 一起安装。


“为什么不直接使用.phar 扩展名?”

我希望能够在没有 .phar 扩展名的情况下将 PHPUnit PHAR 用作二进制文件以使事情更整洁。

【问题讨论】:

    标签: php include require phar


    【解决方案1】:

    为什么第一个版本不起作用

    基于source code,您应该能够使用将phar 标记为可执行文件并在没有扩展名的情况下使用它,但如果您这样做,我不确定您是否可以运行它。

     * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions
     * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats
     * the first extension as the filename extension
     *
     * if an extension is found, it sets ext_str to the location of the file extension in filename,
     * and ext_len to the length of the extension.
     * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells
     * the calling function to use "alias" as the phar alias
     *
     * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the
     * extension rules, not to iterate.
    

    关于“新 phar 的完整路径”的错误是什么意思?

    我认为他们试图传达您不能将部分路径传递给 phar。

    我希望能够将 PHPUnit PHAR 用作不带 .phar 扩展名的二进制文件,以保持简洁。

    您始终可以将 phar 文件符号链接或别名为无扩展名的名称。

    【讨论】:

      【解决方案2】:

      省略使用phar:// 流,因为您正在访问(外部)Phar 文件。使用 phar:// 实际上会尝试访问 Phar 存档中的资源。

      <?php
      $phar = __DIR__ . '/phpunit';
      include $phar;
      assert(class_exists('\\PHPUnit\\Framework\\TestCase'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-29
        • 2019-01-12
        • 2016-11-11
        • 2018-01-21
        • 1970-01-01
        相关资源
        最近更新 更多