繁体   English   中英

使用硬链接时如何防止同一文件被包含两次?

[英]How can I prevent the same file being included twice when using hardlinks?

如何防止同一文件被包含两次? 这是我的源代码:

<?php

error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 0);

if (!file_exists('ccc.php'))
    link('bbb.php', 'ccc.php');
if (!file_exists('ddd.php'))
    link('bbb.php', 'ddd.php');
require_once realpath('ccc.php');
require_once realpath('ddd.php');

$bbb = new Bbb();
echo $bbb->bb();

我收到:

Fatal error: Cannot declare class Bbb, because the name is already in use in /path/to/ddd.php on line 2

它不适用于realpath因为它只返回链接的路径,而不是目标。 我试过readlink但不幸的是它只适用于符号链接。

我有一个可行的解决方案。 这并不理想,但它可以快速修复,直到我能够确保永远不会包含相同的文件两次:

<?php

error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 0);

if (!file_exists('ccc.php'))
    link('bbb.php', 'ccc.php');
if (!file_exists('ddd.php'))
    link('bbb.php', 'ddd.php');

function includeFile($fileName)
{
    foreach (get_included_files() as $file)
    {
        if (fileinode($file) === fileinode($fileName))
            return null;
    }
    require_once $fileName;
}
includeFile('ccc.php');
includeFile('ddd.php');

$bbb = new Bbb();
echo $bbb->bb();

感谢BugFinder建议我使用fileinode

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM