Adam Strudwick
Adam Strudwick

Reputation: 13129

PHP functions variables scope

Say I have...

function one($x){
     return $a + $x;
}

function two(){
     $a = 5;
     echo one(3);
}

Will this show the answer "8" or "3"? In other words, will function one get the value of $a or do I need to declare it global somewhere?

N.B. I haven't tried it yet, but I'm asking it here to understand WHY it acts one way or the other.

Upvotes: 0

Views: 346

Answers (4)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

If you to use a class as close as to your example, Notice no global usage, just assign your variables $this->* then there global scope within the class and its methods/functions you can also access them from outside of the class like $functions->a:

<?php 
Class functions{

    function one($x){
        return $this->a + $x;
    }

    function two(){
        $this->a = 5;
        echo $this->one(3);
    }

}

$functions  = new functions();

$functions->two(); //8

echo $functions->a;//5
?>

Upvotes: 1

Broncha
Broncha

Reputation: 3794

No function one does not know about $a. But this can be done.

$a = 5;

function one($x){
 global $a;
 return $a + $x;
}

function two(){
 global $a;
 $a = 5;
 echo one(3);
}

Now two() would echo 8

Upvotes: 2

Paul
Paul

Reputation: 141829

You won't get 8 or 3. You'll get a Notice since $a has not been defined in the scope of the function one, and you attempt to read it:

PHP Notice:  Undefined variable: a in - on line 3
PHP Stack trace:
PHP   1. {main}() -:0
PHP   2. two() -:11
PHP   3. one() -:8

Upvotes: 1

Amber
Amber

Reputation: 526613

Functions do not inherent scope from the function that calls them. (Nor do they inherit global variables by default - that's what the global keyword is for.)

Thus, $a will be completely undefined inside of one() and you'll get a notice about it.

For more details, see the Variable Scope page in the PHP manual.

Upvotes: 1

Related Questions