PHP: Setters and Getters have died

Last updated 138 days ago by Italo Baeza

php

PHP is very flexible, but sometimes developers don’t want to allow too much flexibility into their libraries for sake of properly using their software as intended. Not because they want to have total control on how to use it, but rather, protect the other developer from f*cking shit up and blaming the author with a nice issue on Github.

Getters and Setters are part of control. Their purpose is (or rather was) very clear: only allow a certain type of variable to be set inside the Class, and retrieve something the developer (safely) expects.

``` class Car
{
/**
* Car Engine
*
* @var CarEngine
*/
protected $engine

/**  
 * Returns the Engine instance  
 *  
 * @return CarEngine  
 */  
public function getEngine() : CarEngine  
{  
    return $this->engine;  
}

/**  
 * Sets a Car Engine  
 *  
 * @param CarEngine $engine  
 * @return void  
 */  
public function setEngine(CarEngine $engine)  
{  
    $this->engine = $engine;  
}

} ```

And now they have died.

How they died? What are you talking about?

PHP 7.4, which is set to be released in November 21 of this year, has introduced typed properties. In a nutshell, a typed property will only allow a certain type of variable to be set inside in the Class property.

For example, let’s say we want the Car class to allow any class that implements the CarEngine interface, like GasEngine or ElectricEngine. As of today, we need one getter and setter for each for this property to force the developer to use only these types, as you saw in the above example.

To avoid meddling with these properties directly, we use the protected keyword. This means, the properties will be able to be accessed only from within the class methods, or other classes that extend it, but not from the outside.

However, if we use typed properties, the Class will only allow that type to be set as a property, killing the purpose of a getter and setter. We don’t need to use it as protected property, we can just set it as public.

```

class Car
{
/**
* Car Engine
*
* @var CarEngine $engine
*/
public CarEngine $engine; // ...

} ```

And we’re not limited to classes. You can also use that for strings, arrays or float types of variables, among the most used.

Read full Article