I have tested the following and it doesn't work. Is there a similar way of achieving this?
A compiling class which formulates a template:
private function include_header () {
function _metadata () {
// Metadata compiler
return $metadata;
}
include (path . "header.php");
}
header.php
<html>
<head>
<?php
_metadata ();
?>
<title>Hello Stackoverflow!</title>
</head>
<body>
...
The _metadata ();
function is only available within the include_header ();
function - nowhere else in the class. I don't want to have to write $this->_metadata ();
in the template file only _metadata ();
. Is that achievable?
Alternatively one could create an external file, for example functions.php
which has the underscore functions specifically for the template - but I'd much rather see if the original query is possible.
Thank you in advance.
From the manual:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
So, essentially, you can't do what you're trying to do. _metadata
will always be a global function if it is defined with the function _metadata() {
syntax. The normal function syntax only supports global functions.
However, PHP 5.3 introduces something called "anonymous functions". These can be assigned to a variable. Since variables can be scoped to a function scope (they are only global if you explicitly say so), you can limit them in this way.
For instance:
$_metadata = function() {
// Metadata compiler
return $metadata;
};
This could then be called in header.php
with:
<?php $_metadata(); ?>
Note that this is less stable: it is, for instance, possible to redefine the variable to be a different anonymous function – or indeed not a function at all. The safest solution, ultimately, is to use a templating language that solves these issues for you. If not, you can either accept that you'll have to use global functions or anonymous functions.
You can't define nested function in PHP. I mean, you can, but there's no purpose since they'll have a global scope and therefore they will be callable from any point of the script.
But you actually don't need to define a _metadata()
function, you can just execute all the function logic inside include_header()
and then store everything in the variable $metadata
, which will be printed in the include with a simple <?php echo $metadata; ?>
.
If you really need to define a function you can use the function create_function()
or (just for PHP > 5.3) an anonymous function
. Since they will be encapsulated inside a variable, which has a function scope, they won't be available outside.