0

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.

  • 1
    Pass it into the constructor like you do with the other value. But don't use hacks like using globals. – Nigel Ren Mar 13 '22 at 07:15

1 Answers1

-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

Anisur Rahman
  • 644
  • 1
  • 4
  • 17