関数 closedir

関数 closedir は、事前に関数 opendir で開かれたディレクトリハンドルを閉じます。これによりハンドルに関連するシステムリソースが解放されます。

構文

phpclosedir(resource $dir_handle): void

例

opendir との基本的な使用法:

php<?php
  $dir = opendir('/path/to/directory');
  if ($dir) {
    // ディレクトリの処理
    closedir($dir); // ハンドルをクローズ
  }
?>

ディレクトリの処理が終了した後は、常にハンドルを閉じてください。

例

try-finally ブロックでの使用:

php<?php
  $dir = opendir('/path/to/directory');
  try {
    // ディレクトリの処理
  } finally {
    if (is_resource($dir)) {
      closedir($dir);
    }
  }
?>

この方法により、例外が発生した場合でもハンドルのクローズが保証されます。

例

scandir 後のハンドルのクローズ:

php<?php
  $dir = opendir('.');
  $files = scandir($dir);
  closedir($dir);
  print_r($files);
?>

関連項目

  • 関数 opendir,
    ディレクトリハンドルを開く
  • 関数 readdir,
    ディレクトリの内容を読み込む
  • 関数 scandir,
    ディレクトリ内のファイルのリストを返す