How does the use of $this differ from global variables in PHP classes?

Using $this in PHP classes refers to the current instance of the class, allowing you to access class properties and methods within the class. Global variables, on the other hand, are accessible throughout the entire script, which can lead to potential naming conflicts and make code harder to maintain. It's generally recommended to use $this to access class-specific data and methods instead of relying on global variables.

class MyClass {
    public $myProperty;

    public function myMethod() {
        $this->myProperty = "Hello";
        echo $this->myProperty;
    }
}

$myObject = new MyClass();
$myObject->myMethod();