1

given this example:

class Example
{
    private $var;

    public function method()
    {
        $this->   here the IDE will offer the var
    }
}

but what if I have this:

class Example
{
    //private $var;

    public function method()
    {
        $this->   var will no longer be offered
    }
}

so in other words, I want code completion works even there is no actually variable. Thats because I want to use with __get method. Unfortunatly, I cant use unset($this->var).

John Smith
  • 6,129
  • 12
  • 68
  • 123

2 Answers2

1

This is an excelent example of a case where you'd use the @property tag. It even mentions the example of the magic methods __get and __set.

In your case it would probably be something like the following:

<?php

class Example
{
    /**
     * @property string $var A variable that can be set and gotten with the magic methods
     */

    public function method()
    {
        $this->var; //here the IDE will offer the var
    }
    
    public function __get($name)
    {
        return $this->$name;
    }
}

?>

Also, take notice of the following:

The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error. As such, there are much more related to error handling. Also note that they are considerably slower than using proper getter and setter or direct method calls.
Gordon on PHP __get and __set magic methods

Community
  • 1
  • 1
Jelmergu
  • 973
  • 1
  • 7
  • 19
0

Because of that points, If we will used protected variable then used this variable to same call and also for child class.