PHP Conference Japan 2024

SplFileInfo::getFilename

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getFilename取得檔案名稱

說明

public SplFileInfo::getFilename(): 字串

取得不包含任何路徑資訊的檔案名稱。

參數

此函式沒有參數。

回傳值

檔案名稱。

範例

範例 #1 SplFileInfo::getFilename() 範例

<?php
$info
= new SplFileInfo('foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('https://php.dev.org.tw/');
var_dump($info->getFilename());

$info = new SplFileInfo('https://php.dev.org.tw/svn.php');
var_dump($info->getFilename());
?>

以上範例的輸出會類似以下:

string(7) "foo.txt"
string(7) "foo.txt"
string(0) ""
string(7) "svn.php"

另請參考

新增註解

使用者貢獻的註解 3 則註解

Alex Russell
9 年前
我試圖找出這個函式和 getBasename (https://php.dev.org.tw/manual/splfileinfo.getbasename.php) 之間的差異,而我唯一能看到的差異是檔案位於檔案系統根目錄下,且根目錄有被指定的情況。

<?php
函式 getInfo($reference)
{
$file = new SplFileInfo($reference);

var_dump($file->getFilename());
var_dump($file->getBasename());
}

$test = [
'/path/to/file.txt',
'/path/to/file',
'/path/to/',
'path/to/file.txt',
'path/to/file',
'file.txt',
'/file.txt',
'/file',
];

foreach (
$test as $file) {
getInfo($file);
}

// 將會回傳:
/*
string(8) "file.txt"
string(8) "file.txt"

string(4) "file"
string(4) "file"

string(2) "to"
string(2) "to"

string(8) "file.txt"
string(8) "file.txt"

string(4) "file"
string(4) "file"

string(8) "file.txt"
string(8) "file.txt"

string(9) "/file.txt" // 注意 getFilename 包含了 '/'
string(8) "file.txt" // 但 getBasename 則沒有

string(5) "/file" // getFilename 同上
string(4) "file" // getBasename 同上
*/

?>
wloske at yahoo dot de
15 年前
應該要說明的是,如果 "filename" 的類型是 "directory",則函式會回傳目錄的名稱。因此

<?php
$info
= new SplFileInfo('/path/to/');
var_dump($info->getFilename());
?>

應該會回傳 "to"

這個函式名稱有點誤導,我很高興我嘗試了它。
khalidhameedkht at gmail dot com
7 年前
// 注意,`filename` 和 `getFilename` 的輸出不同。行為不一致。

$path = 'test.txt';

$pathInfo = pathinfo($path);
echo '<pre>';
print_r($pathInfo);

echo '<br>';
echo '***************';

$splFileInfo = new SplFileInfo($path);
echo '<br>';
echo $splFileInfo->getBasename();

echo '<br>';
echo $splFileInfo->getFilename();
To Top