Jump to content

[SOLVED] calling an include from within a function: variable scope question


Lodius2000

Recommended Posts

Hi all long time no see

 

I tend to keep my layouts in separate files from my main php code and call the layout from within php, most of the time the layout is called within a function also... so heres my problem

 

i have a layout page that contains the code...

headTemplate.php

<html>
<head>
<title><?php print $pagetitle; ?></title>
...it goes on from there

 

now head template gets called from index.php like so

<?php
function show_form($errors = '') {
$pagetitle= "BLAH BLAH BLAH";
require_once('templates/headTemplate.php');
}

show_form();
?>

 

but the BLAH BLAH BLAH is not displayed in the title bar of my window, am I somehow throwing this variable out of scope? what could be wrong?

 

thanks

Link to comment
Share on other sites

variables in user defined functions have a local scope, so the variable you are using to set the title isnt usable by that page.

An alternative would be to do make the variables in your function global, IE:

 

<?php
function show_form($errors = '') {
  global $pagetitle= "BLAH BLAH BLAH";
   require_once('templates/headTemplate.php');
}

show_form();
?>

 

I believe that would make it so that you could use that variable in your other page.

Link to comment
Share on other sites

tang, yes $pagetitle should be passed to headTemplate but it is not.

 

mikesta, good suggestion but it didnt work, you cant declare a global variable and define it in the same line so I broke it apart and that didnjt work, then i defined the var outside the function, then made it global. then I put the global declaration inside of headTemplate at the top and that didnt work either

 

any other suggestions from the crowd, Im not new at this php thing but this is making me nuts.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.