Alexander
Alexander

Reputation: 4219

PHP declaring global variables in function

I've been at this for two hours, perhaps I could ask some help.

Alright, so I have a basic $_POST variable that a user submits. As you can see below, the code first checks if a value was submitted at all, and if not sets it to a default value. If the user did submit a value, it sets a variable (later used) to the value submitted. You can see my code below.

if(!isset($_POST['pSize'])) {
    $pSize = "16"; 
}
else {
    $pSize = ($_POST['pSize']);
};

echo $pSize;

The problem with the above is that I might have 50 or so different areas that the user will submit, and it'd be much nicer to just have myFunction('name','default','value'); than to write out the above for each area. However, I've been running into a problem. Here's a few examples of things I've tried. (excuse any minor errors; I don't have the actual code I tried, just the jist of what I was getting at. The problems of the code I had were not syntax errors).

function newFunction($title, $default, $value)
    if(!isset($_POST[$value])) {
        $title = $default; 
    }
    else {
        $title = ($_POST[$value]);
    };

newFunction('pSize','16,'24');
echo $pSize;

I soon learned that the above won't work due to the fact that variables in a function won't be able to be used outside of that function unless they're global. That makes sense, since if the variable $title could be used, it would be set to many different things depending on how many times I called the function. These things in mind, I tried to set global variables.

function newFunction($title, $default, $value)
    if(!isset($_POST[$value])) {
        global $title . 'Title' = $title; 

...

newFunction('pSize','16,'24');
echo $pSizeTitle;

I lastly tried to set the global variable to the name of the $title I supplied for the function with the string 'Title', creating the new global variable pSizeTitle, so I could echo that variable out. And this probably would have actually worked, except for the fact that I cannot define a global variable with something appended to the end, only with a simple name, and that will not work for me since I need a new global variable for every title item I have.

Hopefully this is clear, sorry if this is an absolute noob problem, I just really can't get past this.

Upvotes: 2

Views: 109

Answers (2)

miken32
miken32

Reputation: 42711

function checkDefault($index, $default)
{
    return isset($_POST[$index]) ? $_POST[$index] : $default;
}

$title = checkDefault("title", "my default value");

Upvotes: 0

Fabio
Fabio

Reputation: 23490

I think the major problem is that you are not returning any data in your function, try to do it

function newFunction($title, $default, $value)
{
    if(!isset($_POST[$value])) {
        $title = $default; 
    } else {
        $title = ($_POST[$value]);
    }
    return $title;
    //return was missed
}

Upvotes: 3

Related Questions