I have a function that display the list of users which is displayUsers().
Basically instead of having 1 different php file for each page, I have used a switch function to load the content like. This is an example of 1 of the pages.
switch($_GET['page']) {
case '#userlist' : $page = '
<div class="innerbox">
displayUsers();
</div> '; break;
}
As you can see it is supposed to show the div tag and load the function, however instead of loading the function, is just displaying the text “displayUsers()”. I understand why it is doing this however I’m not sure how to change it so that is actually runs the function rather that displaying it. Any help would be much appreciated.
Regards
displayUsers()is inside quotes. It’s interpreted as a string. You wantThis concatenates the return value of displayUsers() inside the string, assuming displayUsers() returns the code.
I think you were confusing this feature where variables inside double quoted strings are parsed. This does not work for functions.
You could also use
case '#userlist': $page = sprintf('<div class="innerbox">%s</div>', displayUsers(); break;Read about sprintf here: http://php.net/manual/en/function.sprintf.php
If
displayUsers()actually outputs the code itself, then you can useWhat happens is the opening tag is printed, then the function is called (printing the code), then the closing tag is printed, in that order.
If you’re getting
function not defined()then it’s exactly what it sounds like. The function has not been defined in the current script.How PHP works
Each time a page is requested (someone goes to “foo.php”), your server and PHP engine gets the file (foo.php) from some directory, parses it, and (usually) sends something back to the user in the form of an HTML document. Each page is like a “script”, kind of like a mini application that is compiled, executed once, and forgotten.
So let’s say on your homepage you have
displayUsers()defined.When someone goes to your homepage,
displayUsers()is defined, yay! However, it’s forgotten right afterwards – the PHP engine has discarded the script after it’s loaded and finished, and certainly does not know whatdisplayUsers()is by the time you reachfoo.php.So what can you do?
If you’re only using the function on one page, declare it on that page. Remember, each file is thought of as a script. The PHP engine doesn’t keep track of functions over the user’s session.
If you’re using the function in multiple scripts, include your functions in some “central” file and include it wherever you need it. I really suggest you read more into PHP and
include; I’m not going to explain the basics of PHP; you need to do some more homework.