CakeFest 2024: The Official CakePHP Conference

Phar::setStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::setStubPhar アーカイブの PHP ローダ (あるいは起動スタブ) を設定する

説明

public Phar::setStub(resource|string $stub, int $length = -1): bool

注意:

このメソッドは、php.iniphar.readonly0 でないと Phar オブジェクトで動作しません。それ以外の場合は PharException がスローされます。

このメソッドを使用して、新しい Phar アーカイブに PHP 起動ローダスタブを追加します。あるいは、既存の Phar アーカイブのローダスタブを置き換えます。

Phar アーカイブのローダスタブは、 このようにアーカイブを直接インクルードした際に使用されます。

<?php
include 'myphar.phar';
?>

phar ストリームラッパーを使用して次のようにファイルをインクルードした際には、 ローダにはアクセスしません。

<?php
include 'phar://myphar.phar/somefile.php';
?>

パラメータ

stub

文字列あるいはオープンしたストリームハンドル。 この phar アーカイブの実行スタブとして使用します。

length

戻り値

成功した場合に true を、失敗した場合に false を返します。

エラー / 例外

php.ini で phar.readonly が有効になっている場合に UnexpectedValueException がスローされます。 変更をディスクに書き込む際に何らかの問題が発生した場合は PharException がスローされます。

変更履歴

バージョン 説明
8.3.0 resourcelength を渡して Phar::setStub() をコールすることは、 推奨されなくなりました。 $phar->setStub(stream_get_contents($resource)); に置き換えるべきです。

例1 Phar::setStub() の例

<?php
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['a.php'] = '<?php var_dump("Hello");';
$p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include
'phar://brandnewphar.phar/a.php';
var_dump($p->getStub());
$p['b.php'] = '<?php var_dump("World");';
$p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include
'phar://brandnewphar.phar/b.php';
var_dump($p->getStub());
} catch (
Exception $e) {
echo
'brandnewphar.phar での書き込み操作に失敗しました: ', $e;
}
?>

上の例の出力は以下となります。

string(5) "Hello"
string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
string(5) "World"
string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"

変更履歴

バージョン 説明
5.4.0 len パラメータが追加されました。

参考

add a note

User Contributed Notes 3 notes

up
1
Scott Dutton
6 years ago
Its not clear in the docs but __HALT_COMPILER() is required in the stub.
up
0
Olivier Laviale
12 years ago
If your stub has a namespace, it is used for each include that doesn't define one.
up
0
jaimz22 at gmail dot com
16 years ago
One thing I had alot of problems with, is that i can't set the stub unless I put the whole operation inside of a try/catch block!

If i remove the try/catch block it will error our and not write the stub with the content i want it to have.
To Top