0

I am building an image gallery using php. The code I am using is like:

function ImageBlock() {
    $dir = 'img-gallery';
    $images = scandir($dir);
    $classN = 1;
    foreach ($images as $image) {
        if ($image != '.' && $image != '..') {
            echo '<img class="image' . $classN . '" src="img-gallery/' . $image . '" width="300px" 
                  height="300px">';
        }
        $classN++;
    }
}

if I call this function in another file it works. My question is if I use the cose below, declaring the variables out of function ...it does not work anymore:

$dir = 'img-gallery';
$images = scandir($dir);

function ImageBlock() {
    $classN = 1;
    foreach ($images as $image) {
        if ($image != '.' && $image != '..') {
            echo '<img class="image' . $classN . '" src="img-gallery/' . $image . '" width="300px"  
        height="300px">';
        }
        $classN++;
    }
}

Why, I mean a variable declared outside should have a global scope to my knowledge, and should ne accesible from within the function. Isn't it so ?

Vahid Hallaji
  • 7,159
  • 5
  • 42
  • 51

1 Answers1

2

PHP is not JavaScript. Functions in the global namespace are not available inside of functions unless you explicitly make them so. There are three ways to do this:

Pass them as a parameter (recommended)

function ImageBlock($images){

Use the global keyword (strongly not recommended)

function ImageBlock(){
    global $images

Use the $GLOBALS superglobal (strongly not recommended)

function ImageBlock(){
    $images = $GLOBALS['images'];
John Conde
  • 217,595
  • 99
  • 455
  • 496