How to get a variable from another function

me123 picture me123 · Feb 19, 2010 · Viewed 20.7k times · Source

I am new to PHP and I am trying to create a web mashup with amazon and ebay. My problem is that I have a function called "printCategoryItems()" which sets a variable called $keyword. I want to use this variable elsewhere in the code but I can't get it to work. For Example,


<?php
function printCategoryItems(){
    if(isset($_GET['keyword'])){
        $keyword = $_GET['keyword'];
        ...
    }
}
...

$query = $keyword;

...

This is the sort of thing I am trying to do but I end up getting an Undefined variable error for keyword. Is there a way for me to do what I'm trying to do?

Thanks for your help in advance.

(Only have Java Programming Experience)

Answer

Pascal MARTIN picture Pascal MARTIN · Feb 19, 2010

You could use the global keyword in the function, so $keywords inside the function refers to $keywords outside the function :

function printCategoryItems() {
    global $keyword;
    if(isset($_GET['keyword'])){
        $keyword = $_GET['keyword'];
    }
}

printCategoryItems();
var_dump($keyword);

This is because variables inside a function belong to the local-scope of the function, and not the global scope (I haven't done any JAVA for a long time, but I think it's the same in JAVA : a variable declared inside a function is not visible from outside of that function).


But using global variables is generally not a great idea... a better solution would be to have your function return the data ; for instance :

function printCategoryItems() {
    if(isset($_GET['keyword'])){
        return $_GET['keyword'];
    }
}

$keyword = printCategoryItems();
var_dump($keyword);


As a semi-side-note : another solution, still with global variables (not a good idea, again) would be to use the $GLOBALS superglobal array :

function printCategoryItems() {
    if(isset($_GET['keyword'])){
        $GLOBALS['keywords'] = $_GET['keyword'];
    }
}

printCategoryItems();
var_dump($GLOBALS['keywords']);

Here, no need for the global keyword anymore.


And, to finish, you should read the PHP documentation -- especially the part about Functions.