13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

デストラクタだけカレントディレクトリが違う

Last updated at Posted at 2014-06-06
	class HOGE{
		public function __construct(){
			var_dump(getcwd());
		}
		public function fuga(){
			var_dump(getcwd());
		}
		public function __destruct(){
			var_dump(getcwd());
		}
	}
	
	$hoge = new HOGE(); // C:\path\to\DocumentRoot\test
	$hoge->fuga(); // C:\path\to\DocumentRoot\test
	 // C:\xampp

PHPのシャットダウン中にデストラクタが呼ばれた場合、カレントディレクトリがサーバのルートに変わってしまいます。
chdir()等でカレントディレクトリを変更していた場合にも元に戻ってしまいます。

まあデストラクタの問題というよりはシャットダウン処理の仕様で、register_shutdown_function()でも同じ現象が発生します。

	register_shutdown_function(function(){
		var_dump(getcwd()); // C:\xampp
	});

ここまでであれば、相当わかりにくいけどどうにか納得できないこともない。
そういう仕様ならそれに合わせるしかあるまい。

    class HOGE{
        public function __construct(){
            var_dump(getcwd());
        }
        public function fuga(){
            var_dump(getcwd());
        }
        public function __destruct(){
            var_dump(getcwd());
        }
    }

    $hoge = new HOGE(); // C:\path\to\DocumentRoot\test
    $hoge->fuga(); // C:\path\to\DocumentRoot\test
    $hoge = 1; // C:\path\to\DocumentRoot\test

    $hoge = new HOGE(); // C:\path\to\DocumentRoot\test
    $hoge->fuga(); // C:\path\to\DocumentRoot\test
	// C:\xampp

なんてこった。
これはあかんで。
こちらはスクリプト中でデストラクタが呼ばれるため、カレントディレクトリが継続しています。

回避手段としては、デストラクタでディレクトリ/ファイルを扱わないというのもありますが、仕様上難しいこともあるでしょう。
まあ実用的には、
・コンストラクタあたりでフルパスを定義しておいて、以後はそれを使う
で問題ないでしょう。

なおディレクトリ名がC:\になっているのはXAMPPを使っているからで、Linux環境でも再現します。
getcwd()が/とかになる。

13
13
7

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?