Вопрос

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