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
https://forums.phpfreaks.com/topic/89503-solved-functions-and-variable-scope/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.