rfc:automatic_get_set_methods

Request for Comments: Automatic get/set methods for objects

Introduction

Currently, PHP only allows for defining functionality during access to properties on an object when those properties are not defined in the class. This proposal will outline a suggested change to PHP's behaviour when dealing with object properties which will allow for compact code when necessary, and easy refactoring of code when necessary with a minimum of fuss.

Proposal version 1

When a class is initialized at runtime, each property will have a 'get' and a 'set' method created for it which will handle basic 'get/set' functionality. If a get or set method exists for the given property, then the corresponding auto-generated method would not be auto-generated.

Proposal version 2

When a property on an object is attempted to be read, the PHP engine will look for a corresponding getXXX() method for the given property. If one exists, that methods will be executed. If not, the property will be returned (subject the public/protected/private visibility). Similarly, when a property on an object is attempted to be set, the PHP engine will look for a corresponding setXXX() method. If one exists, that method will be executed. Otherwise, the property will be set normally (subject to public/protected/private visibility).

Benefits

This will allow for standard PHP code with property access logic to be written without the need for writing corresponding boilerplate get/set methods up front. Only when non-standard or extra logic needs to be applied to a property during reading or writing would get/set methods for those properties need to be written. This will reduce code size and make it more clear that 'out of the ordinary' logic is happening in the given code.

Also, when dealing with existing classes that are not written with traditional get/set methods for each property, this proposed change would make it easier to add in new functionality without the need for extensive refactoring of code that's using the classes in question. For example, rather than needing to update code such as $calendar→dayOfWeek to be $calendar→getDayOfWeek() in the calling code, the code using the calendar library can remain untouched, and a getDayOfWeek() method can be added to the calendar class, introducing some extra functionality in the calculation of the day of the week (in this example).

Changelog

Initial draft. Full idea not fleshed out entirely with code examples yet.

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