-3

Is there any way we can create another property in class (i.e. $myVar), which wouldn't need to prepend $this-> and can be called directly (like $this is used), i.e.:

...
public function hello()
{
    echo $myVar;  //instead of $this->myVar
}

Please note, I clearly emphasize that "creating local variables inside method" is out of the question.

Dharman
  • 30,962
  • 25
  • 85
  • 135
T.Todua
  • 53,146
  • 19
  • 236
  • 237

1 Answers1

0

You cannot access property without specifying its scope. If you refer to it by its name, you are referring to a local variable.

To access properties you need to use -> (Object Operator). Static properties are accessed using the :: (Double Colon; also called Paamayim Nekudotayim).

If you would like to access a property inside of a class method you would use either of these two operators in connection with scope keyword. To access the scope of the current object within one of its methods, you can use the pseudo-variable $this. For static properties, you would use self or static to refer to the current class. To access the parent class, you would use parent. Combining all of it:

class B{
    static protected $s1;
}

class A extends B {
    protected $v1 = 'foo';
    static protected $s1;
    static private $s2;

    public function __construct()
    {
        print_r($this->v1);
        print_r(parent::$s1);
        print_r(self::$s1);
        print_r(static::$s2);
    }
}

For more information, see: PHP: self:: vs parent:: with extends

However, nothing stops you from creating new local variables inside class methods.

class C {
    private $var1 = 'bar';

    public function func() {
        $var1 = 'foo';
        print_r($var1); // This is 'foo' not 'bar'
    }
}

It all comes down to the scope in which the variable resides. You have different operators and keywords for each scope resolution, but you can create local variables as you would anywhere else in the code.

Dharman
  • 30,962
  • 25
  • 85
  • 135