W3docs

PHP class: Global variable as property in class

You can use the global keyword to access a global variable inside a class.

You can use the global keyword to access a global variable inside a class. Here's an example:

Example of a global variable as property in a PHP class

<?php

$x = 1;

class MyClass
{
  public $y;

  public function __construct()
  {
    global $x;
    $this->y = $x + 1;
  }
}

$obj = new MyClass();
echo $obj->y; // Outputs 2

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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.