treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] My dumb function is not working and there's nothing wrong with it either, at least not obviously...

  • Hi guys,

    I'm calling a functions.php at the top of my file and then calling some variables right after.

    Then I use the functions, mainly of include and echo functions, in the page somewhere. The functions work based on the fact that the variable exists.

    For example:

    functions.php

    <?php

    function the_title()
    {
    $title = "Hello world";
    $title .= $page_title; //$page_title is declared in the webpage
    echo $title;
    }

    ?>


    index.php

    <?php include("functions.php"); ?>
    <?php

    $page_title="this is my index page.";

    ?>

    <html>
    bleh bleh all the head tags and stuff...

    <div id="title"><?php the_title(); ?></div>

    bleh bleh all the closing tags...

    </html>


    Now you get my situation.

    The two functions that don't work are:


    function the_name()
    {
    echo $level_name;
    }

    function the_page()
    {
    echo $level_page;
    }


    Don't they look perfectly legit?

    The variables are declared in the same way--



    <?php include("functions.php"); ?>
    <?php

    $level_number = "";

    $level_name = "Welcome!";

    $level_page = "Home Page";

    ?>



    that's everything before my <!DOCTYPE>.

    Now when I call the function:


    <span><?php the_name(); ?></span>


    It doesn't work. The page still loads--means there's no syntax problem. The function just doesn't echo anything. So what's wrong? All looks legit...

    Additional info: If I abort the function and just call "echo $level_name;", it works. So it's something with my function...

    Red
  • Ah...

    I see...

    Something has to do with my functions.php wants to know the variables before it runs itself?

    can someone clarify and tell me how I can achieve what I'm trying to achieve?
  • Your issue is one of scope. Inside your functions, any variables declared externally are not known unless their value is passed as a parameter of the function or accessed using GLOBAL within the function.

    Regards,


    Michael
  • Yes, thanks! I figured out the parameter part yesterday. How come I never thought of that?...*headdesk*