LoginSignup
0
0

More than 3 years have passed since last update.

realpathの謎な挙動

Last updated at Posted at 2020-12-09

※自ブログ (https://fujitatakesh.blogspot.com/2020/12/php-realpath.html) からの転載です。

これにハマっていました。

PHP の realpath、相対パスから実際のパスに直してくれる関数です。Classic ASP では Server.MapPath というのがありましたが、realpath では実在するもののみ返す性質があります。

さて、今回、謎な現象があったので調査しました。以下のように数か所に realpath を置き、いったい「何」がおきているのか調査します。

<?php
echo 'Normal:'.realpath('').'<br>';
$cls = new stab();
$cls->main();

class stab {
  function __construct() {
    echo 'In constructor:'.realpath('').'<br>';
  }
  function main() {
    echo 'In class method:'.realpath('').'<br>';
  }
  function __destruct() {
    echo 'In destructor:'.realpath('').'<br>';
  }
}

realpath('') で現在の絶対パスを返してくれるわけですが、想定ではすべて同じものが返ってほしいです。ところが、上記のようにクラスインスタンス内では、ある場所だけ違うものが返されます。

その答えはデストラクタ。インスタンスが無くなって初期値がプログラムフォルダになっていることが考えられます。

Normal:C:\inetpub\sites\wwwroot
In constructor:C:\inetpub\sites\wwwroot
In class method:C:\inetpub\sites\wwwroot
In destructor:C:\Program Files (x86)\PHP\v7.1

デストラクタ内で使うときは、コンストラクタで予め親パスを変数に退避させておいて、realpath 使用時はくっつけてあげるのがよいでしょう。


コメントで返信いただいたとおり、スクリプトの終了時、かつクラスの終了時におきる現象で、インスタンス変数を必ず終了時にクリアすると正常な応答になりました。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0