dramasea
dramasea

Reputation: 3490

inner function can't call the variable of the outer function in php

<?php

   function a(){

     $a = "hello";
      function b(){
          global $a;
          echo $a . " World";
      }
      b();
   }

   a();

?>

This is my code, it only echo " World" even I have use the global keyword to include the $a. Why?

Upvotes: 2

Views: 324

Answers (3)

DLastCodeBender
DLastCodeBender

Reputation: 327

please note that variables are not passed to functions by default unless otherwise specified e.g. use

function a($b){ //code } 

instead of just

function a(){ //code } 

I think that might be the problem you are facing.

Upvotes: 0

Manish Jesani
Manish Jesani

Reputation: 1357

function a call first after call call function b. if you pass parameter in function b or set as globel $a in function a

set as globel $a in function a() because this variable use in finction b without passing parameter and set globel $a in function b because not define this variable this function

<?php

   function a(){
     global $a;
     $a = "hello";
      function b(){
         global $a; 
          echo $a . " World";
      }
      b();
   }

   a();
?>

or you can use

<?php

   function a(){

     $a = "hello";
      function b($a){

          echo $a . " World";
      }
      b($a);
   }

   a();

?>

Upvotes: 0

mathk
mathk

Reputation: 8143

You have to tell which variable from the outer scope you want to use.

<?php

   function a(){

     $a = "hello";
      function b() use ($a){
          echo $a . " World";
      }
      b();    }

   a();

?>

Upvotes: 4

Related Questions