Lei Lionel Lei Lionel - 6 months ago 14
PHP Question

Use a variable declared in a function outside that function

I have created a function using PHP which looks like this

<?php

function addImage($imageFolder, $imageName) {

global $imageName;

$imageName = 'stackoverflow'.$imageName;

if (condition) {

global $imageFolder;

$imagePath = $imageFolder.''.$imageName;

if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {

return true;

}

}
}

if(addImage('image/', $imageName)){

echo $imageName;
echo $imageFolder;
}

?>


The problem I am facing is that, I am able to get
$imageName
outside the function but unable to get
$imageFolder
(
var_dump($imageFolder)
displays
null
). I am new to the
global variable
and I really don't know if I am using it correctly

Answer

The issue is that the global keyword doesn't make an existing variable a global one. Instead, it tells PHP that when you refer to a variable by that name, it should look in the global scope.

You have two options to fix this:

1. Use different variable names for parameters than you do for the globals

<?php

function addImage($imgFolder, $imgName) {

    global $imageName;

    $imageName = 'stackoverflow'.$imgName;

    if (condition) {

        global $imageFolder;
        $imageFolder = $imgFolder;

        $imagePath = $imageFolder.''.$imageName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {

            return true;

        }

    }       
}

if(addImage('image/', $imageName)){

    echo $imageName;
    echo $imageFolder;
}

?>

2. Use the $GLOBALS variable

<?php

function addImage($imageFolder, $imageName) {
    $imageName = 'stackoverflow'.$imageName;
    $GLOBALS['imageName'] = $imageName;

    if (condition) {
        $GLOBALS['imageFolder'] = $imageFolder;

        $imagePath = $imageFolder.''.$imageName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {

            return true;

        }

    }       
}

if(addImage('image/', $imageName)){

    echo $imageName;
    echo $imageFolder;
}

?>

3. Don't use globals (probably a better solution) [Thanks Robbie Averill]

<?php

function addImage($imageFolder, $imageName) {
    $imageName = 'stackoverflow'.$imageName;

    if (condition) {

        $imagePath = $imageFolder.''.$imageName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {

            return $imageName;

        }

    }  
    return false;
}

$imageFolder = 'image/';
if($imageName = addImage($imageFolder, $imageName)){

    echo $imageName;
    echo $imageFolder;
}

?>