문제

I am facing some errors with use of global variables. I defined a $var in global scope and trying to use it in functions but it not accessible there. Please see below code for better explanation:

File a.php:

<?php

  $tmp = "testing";

  function testFunction(){
     global $tmp;
     echo($tmp);
  }

So a bit about how this function is called.

File b.php:

<?php
  include 'a.php'
  class testClass{
    public function testFunctionCall(){
        testFunction();
    }
  }

The above 'b.php' is called using:

$method = new ReflectionMethod($this, $method);
$method->invoke();

Now the desired output is 'testing' but the output received is NULL.

Thanks in advance for any help.

도움이 되었습니까?

해결책

You missed calling your function and also remove the protected keyword.

Try this way

<?php

  $tmp = "testing";

  testFunction(); // you missed this

  function testFunction(){  //removed protected
     global $tmp;
     echo($tmp);
  }

Same code but using $GLOBALS, gets you the same output.

<?php

$tmp = "testing";

testFunction(); // you missed this

function testFunction(){  //removed protected
    echo $GLOBALS['tmp'];
}

다른 팁

This protected function can't access the variable. So use by removing protected.

<?php

  $tmp = "testing";

   function testFunction(){
     global $tmp;
     echo ($tmp);
  }

protected functions need to be in a class like this:

 Class SomeClass extends SomeotherClass {

   public static $tmp = "testing";

   protected function testFunction() {

      echo self::$tmp;

   }
}

I was having the same problem here. As $GLOBALS is seen within any function I used this :

<?php

  $GLOBALS['tmp'] = "testing";

  function testFunction(){

     echo( $GLOBALS['tmp'] );
  }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top