从包含页面回显文件名

Echoing file name from include page

我认为我的问题没有提供足够的见解。

基本上。我希望回显文件名,即使此函数将从我的 header.php 文件中调用。

这里有一些代码可以帮助您理解:

index.php

      <?php include 'functions.php'; ?>

      <!DOCTYPE html>
      <html lang="en-gb">
        <?php getHeader(); // Get header ?>
      </html>

functions.php

    <?php

    // Get header
    function getHeader(){
        include 'header.php';
    }

    // Get filename
    function pageTitle(){
        echo ucfirst(basename(__FILE__, '.php'));
    }

    ?>

最后...

header.php

<head>
    <title><?php pageTitle(); ?></title>
</head>

但是,问题来了,因为代码 echo ucfirst(basename(__FILE__, '.php')); 在我的 functions.php 文件中,它只是回显 functions.php 文件名。

关于如何使其回显 'index' 而不是 'functions' 的任何想法?

提前致谢。

__FILE__ 将为您提供 当前 .php 页面 的文件系统路径,而不是一个你把它包括在内的地方。只需将文件名传递给 getHeader() 函数,如下所示:

index.php

<?php include 'functions.php'; ?>

<!DOCTYPE html>
<html lang="en-gb">
<?php getHeader(ucfirst(basename(__FILE__, '.php'))); ?>
</html>

随后按以下方式更改 functions.phpheader.php 文件,

functions.php

<?php
    // Get header
    function getHeader($file){
        include 'header.php';
    }

    // Get filename
    function pageTitle($file){
        echo $file;
    }
?>

header.php

<head>
    <title><?php pageTitle($file); ?></title>
</head>

您必须在 index.php 中定义一个包含文件名的变量,然后对 return 文件名使用相同的变量,例如:

index.php

<?php $includerFile = __FILE__; ?>
<?php include 'functions.php'; ?>

<!DOCTYPE html>
<html lang="en-gb">
<?php getHeader(); // Get header ?>

functions.php

<?php

    // Get header
    function getHeader(){
        include 'header.php';
    }

    // Get filename
    function pageTitle(){
        echo ucfirst(basename($includerFile, '.php'));
    }

?>

为了使它更系统,你可以这样做:

这实际上只是 PHP 模板引擎的一个特例。考虑拥有这个功能:

index.php

<?php

    function ScopedInclude($file, $params = array())
    {
        extract($params);
        include $file;
    } 

    ScopedInclude('functions.php', array('includerFile' => __FILE__));

?>

<!DOCTYPE html>
<html lang="en-gb">
<?php getHeader(); // Get header ?>