Jump to content

[SOLVED] Functions and variable scope


digitalgravy

Recommended Posts

I wrote a function that will return the search query from the referring url.  I will use Google in my example.

 

The function is in a required include file full of functions, it is not behaving like I expect.  I need a little help.

 

I am able to get the value I want, but I am not able to return the value.

 

The function if as follows:

<?php
function searchQuery($urlPart) {
     // Parse search query from url
     $fullQuery = $urlPart['query'];
     parse_str($fullQuery, $queryPart);
     // Decode query portion of url
     // q for google and msn - p for yahoo
     if (isset($queryPart['q'])) {
         $query = $queryPart['q'];
         echo $query;  // Added to see if $query is what I expect, will remove when I am able to return on next line
         return $query;
     } elseif (isset($queryPart['p'])) {
         $query = $queryPart['p'];
         echo $query; // Added to see if $query is what I expect, will remove when I am able to return on next line
         return $query;
     }
}
?>

 

I do a function call as follows:

<?php
require($_SERVER["DOCUMENT_ROOT"] . '/functions.php');
$referrer = "http://www.google.com/search?q=Test+Query%2C+Test&sourceid=navclient-ff&ie=UTF-8&rlz=1B3GGGL_enUS221US221";
$urlPart  = parse_url($referrer);

searchQuery($urlPart);

echo $query;

?>

 

The above code gives me:

The echoed query from the function "Test Query, Test" and

Notice: Undefined variable: query in /home/path/to/test.php on line 8

 

I am not sure what I am doing wrong.

 

I require the functions include

I define the variable

I call the function and pass the variable as an argument

I try and use the returned value.

 

Am I missing something?

Am I not understanding variable scope?

 

Thanks in advance.

 

 

 

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.