rfc:abstract_final_class

This is an old revision of the document!


PHP RFC: Static classes

Introduction

Static classes are helpful in the case you are wrapping common functions that are static, but the common class itself cannot be instantiated. Currently, PHP developers' only resource is to create a final class with a private constructor, leading to untestable and error prone code.

When untestable/error prone code is mentioned is that there's no signaling of broken definition by creating a regular class with private constructor and other members are not declared as static. Everything will just compile smoothly (file inclusion/autoloading).

By the acceptance of this patch, every method declaration would automatically be enforced to behave as static without any further keyword needed. This reduces the human error of methods being forgotten to be declared as static.

For such, here is motivation:

  • As “static”, it purely behaves at class level, not at instance level
  • Could also be used with combination of “final”, meaning it cannot be extended (such as more permissive visibility, behavior change, etc)
  • There's no way of adding static variables to a namespace. This would address this issue too.

Proposal

Change language scanner to accept static class construction, and subsequently enforcing the existence of only static members.

Proposed PHP Version(s)

PHP 7

Example

final static class Environment
{
    private static $rootDirectory = '/var/www/project';
    public static function getRootDirectory()
    {
        return self::$rootDirectory;
    }
}
echo Environment::getRootDirectory();

Vote

Static classes
Real name Yes, as "static class" Yes, as "abstract final class" No
ab (ab)   
ajf (ajf)   
bwoebi (bwoebi)   
derick (derick)   
dm (dm)   
dragoonis (dragoonis)   
guilhermeblanco (guilhermeblanco)   
hywan (hywan)   
jedibc (jedibc)   
jpauli (jpauli)   
kalle (kalle)   
kinncj (kinncj)   
krakjoe (krakjoe)   
levim (levim)   
malukenho (malukenho)   
sebastian (sebastian)   
stas (stas)   
Count: 5 0 12


The vote starts on 12/12/2014 and ends on 12/19/2014. 2/3 majority required.

Implementation

Most recent suggested implementation available at https://github.com/php/php-src/pull/929 Originally suggested as abstract class at https://github.com/php/php-src/pull/923

rfc/abstract_final_class.1418399174.txt.gz · Last modified: 2017/09/22 13:28 (external edit)