'access variable outside a class [duplicate]

I want to try accessing an outside variable from a class object. how can it be possible?

my code:

<?php 
  $variable = "vikrant";
  class greet {
     public function __construct($name){
        echo "hello - {$name}--{$variable}";
     }
  }
  $message = new greet("vijay");
  

?>

this thing doesn't work. but I need to know how to achieve it.



Solution 1:[1]

Use php superglobal $GLOBALS. $GLOBALS - References all variables available in global scope.

$variable = "vikrant";
class greet {
  public function __construct($name){
     echo "hello - {$name}--{$GLOBALS['variable']}";
  }
}
$message = new greet("vijay");//hello - vijay--vikrant

$GLOBALS

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anisur Rahman