Skip to content
PHP Logo

How can class variables be declared and utilized in PHP to avoid undefined property errors?

To avoid undefined property errors when working with class variables in PHP, you can declare them within the class definition using the `public`, `protected`, or `private` keywords. This ensures that the variables are properly initialized and accessible within the class methods. By declaring class variables explicitly, you can prevent undefined property errors and ensure that your code is more robust and maintainable.

php
class MyClass {
    public $myVariable;

    public function __construct() {
        $this->myVariable = 'Hello World';
    }

    public function getVariable() {
        return $this->myVariable;
    }
}

$obj = new MyClass();
echo $obj->getVariable(); // Output: Hello World