PHP

PHP

By DeepSource

Visibility should be explicitly declared PHP-W1088

Bug risk
Autofix

Visibility (also know as Access Modifiers) can be used to define where it can be accessed. There are three access modifiers available in PHP:

  • public - The class members can be accessed from everywhere. This is default.
  • protected - The class members can be accessed within the class and by classes derived from that class.
  • private - The class members can only be accessed within the class.

The class members(properties, constants, or methods) declared without any explicit visibility keyword are by default considered as public. It is recommended to set visibility explicitly, which increases code readability. In addition, it gives the developer a mental model of where the class member would be accessible, which also leads to a better API design and makes sure that you are not making something public which isn't supposed to be. Also, as per PSR-12: Extended Coding Style, visibility should be explicitly declared with all class properties, constants and methods.

Example

Bad practice

class User
{
    var $name;

    const STATUS_ACTIVE = 1;

    function setName(string $name)
    {
        $this->name = $name;
    }
}

Recommended

class User
{
    public $name;

    public const STATUS_ACTIVE = 1;

    public function setName(string $name)
    {
        $this->name = $name;
    }
}