Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP class properties without "$this"

Tags:

php

Ss is possible, to access class properties inside this class methods without using "$this", like in C++?

Small example:

class MyClass
{
    protected $foo = 'abc';
    protected $bar = 'dca';

    public function __construct()
    {
        $foo = 'Hello';
        $bar = 'World!';
    }

    public function display()
    {
        echo $foo . ' ' . $bar;
    }
}


$MyObject = new MyClass();
$MyObject->display();

In result, I have notices about undefined variables. But I'ld like to be sure - is it possible, or not?


1 Answers

No. It is not. In PHP, you have to use the $this-> syntax to access instance variables.

like image 69
Brian Warshaw Avatar answered Jun 10 '26 14:06

Brian Warshaw