phpconstructorvisibilitypsr-2

PSR and constructor visibility


According to PSR-2

Visibility MUST be declared on all properties and methods

but what about __construct, it's specific function and I was wondering if it should also be marked by default as public when we're using PSR?


Solution

  • Yes you should also declare visibility for the __construct() method. In some cases the __construct is not public like

    abstract class Singleton {
    
        private static $instances;
    
        final public static function getInstance() {
            $className = get_called_class();
    
            if(isset(self::$instances[$className]) == false) {
                self::$instances[$className] = new static();
            }
            return self::$instances[$className];
        }
    
        protected function  __construct() { }
    
    }