PHP class: Global variable as property in class
You can use the global
keyword to access a global variable inside a class. Here's an example:
<?php
$x = 1;
class MyClass
{
public $y;
public function __construct()
{
global $x;
$this->y = $x + 1;
}
}
$obj = new MyClass();
echo $obj->y; // Outputs 2
Watch a video course
Learn object oriented PHP
Keep in mind that using global variables in this way can make your code less modular and more difficult to maintain. It's generally a better practice to pass any variables that a class needs as arguments to its methods or to its constructor.