Include PHP PHAR without .phar extension

孤街浪徒 提交于 2020-01-24 22:23:04

问题


I'm having trouble including a PHAR into my application bootstrapping code. I'm attempting to include the phpunit/phpunit PHAR to have the PHPUnit classes available in my application.

Given I have the following directory structure:

/path/to/code/
    app.php
    phpunit

Where phpunit is the PHPUnit as a PHAR, and app.php contains:

<?php

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

include $phar;

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

I get the following error:

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

But when I rename the PHAR to phpunit.phar, and include that instead using

<?php

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

include $phar;

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

The code works fine, and the TestCase class exists.

Why doesn't the first version work, and what does the error about "full path to a new phar" mean?


My PHP version is 7.2, and the PHPUnit PHAR is on version 7.* which has been installed with Phive.


"Why don't you just include using the .phar extension?"

I want to be able to use the PHPUnit PHAR as a binary without the .phar extension to keep things cleaner.


回答1:


Why doesn't the first version work

Based on the source code, you should be able to use a mark the phar as executable and use it without an extension, but if you do that, I am not sure you can run it.

 * 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.

what does the error about "full path to a new phar" mean?

I think they are trying to convey that you cannot pass a partial path to a phar.

I want to be able to use the PHPUnit PHAR as a binary without the .phar extension to keep things cleaner.

You could always just symlink or alias the phar file to an extensionless name.



来源:https://stackoverflow.com/questions/59302726/include-php-phar-without-phar-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!