Allen S
Allen S

Reputation: 3539

PHP: Global var not being picked up inside a function

This is blowing my mind...

I've got a standalone PHP file, and a simple function with a global var.

<?php
    $var = 4;

    function echoVar()
    {
        echo $var; 
    }

    echoVar();
?>

When I call echoVar() nothing is returned... However if I place the $var inside the function it will return 4.

What's going on here? Shouldn't $var be global in this case?

Upvotes: 1

Views: 157

Answers (5)

Terry Harvey
Terry Harvey

Reputation: 9444

If a variable is set outside of a function, it's not visible inside that function. To access it, you must declare it global with the global keyword. This is called a scope.

<?php

$var = 4;

function echoVar() {
    global $var;

    echo $var;
}

echoVar();

Note: This is generally considered bad practice. Read this for more information.

A good alternative would be to pass in the variable as an argument:

<?php

$var = 4;

function echoVar($var) {
    echo $var;
}

echoVar($var);

Upvotes: 5

Dave
Dave

Reputation: 3288

Just going to clarify since everyone seems to be posting mostly rubbish.

  • Do not use global $var;
  • Do not echo out inside of a function
  • Output from a function does not need to be assigned to a variable before being echo'd

This is how it "should" be done.

<?php
    $var = 4;  //set initial input var this is external to the function

    function echoVar($internalvar) {  /*notice were accepting $var as $internalvar I'm doing this to clarify the different variables so you don't end up getting confused with scope  $internalvar is local to the function only and not accessible externally*/
        return $internalvar; //now we pass the function internal var back out to the main code we do this with return you should never echo out your output inside the function
    }

    echo echoVar($var);  //call function and pass $var in as an arguement
?>

Upvotes: 0

Martin C
Martin C

Reputation: 395

When you call any function it's create local variable so you have to pass argument in calling function part.

    $var = 4;

    function echoVar($var)
    {
        echo $var; 
    }

    echoVar($var);

Upvotes: 0

Ana Claudia
Ana Claudia

Reputation: 507

You can either have $var as an argument, like this:

$var = 4;

function echoVar($var)
{
    echo $var; 
}

echoVar($var);

or use global, like this:

$var = 4;

function echoVar()
{

    global $var;
    echo $var; 
}

echoVar();

Upvotes: 0

superphonic
superphonic

Reputation: 8074

Lots of options here... like

<?php
    $var = 4;

    function echoVar($var)
    {
        echo $var; 
    }

    echoVar($var);
?>

or

<?php
    $var = 4;

    function echoVar()
    {
        global $var;
        echo $var; 
    }

    echoVar();
?>

Upvotes: 3

Related Questions