Reputation: 53
I don't think my question really gives enough insight.
Basically. I'm looking to echo the file name, even though this function will be called from my header.php file.
Here's some code to help you understand:
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'));
}
?>
And finally...
header.php
<head>
<title><?php pageTitle(); ?></title>
</head>
But, here's the problem, because the code echo ucfirst(basename(__FILE__, '.php'));
is in my functions.php
file, it just echo's the functions.php filename.
Any ideas on how to make it echo 'index', rather than 'functions'?
Thanks in advance.
Upvotes: 1
Views: 294
Reputation: 439
You have to define a variable in index.php that contains the file name and then use the same variable to return filename like:
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'));
}
?>
To make it more systematic you can do it this way:
This is actually just a special case of what PHP templating engines do. Consider having this function:
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 ?>
Upvotes: 0
Reputation: 16963
__FILE__
will give you the file system path of the current .php page, not the one where you've included it. Simply pass the file name to getHeader()
function, like this:
index.php
<?php include 'functions.php'; ?>
<!DOCTYPE html>
<html lang="en-gb">
<?php getHeader(ucfirst(basename(__FILE__, '.php'))); ?>
</html>
Subsequently change your functions.php and header.php file in the following way,
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>
Upvotes: 1