lundi 9 septembre 2019

How to distinguish between unspecified and specified parameters in PHP methods?

I find myself pondering this from time to time, so I thought I'd ask for some community input. Given the following PHP method:

/**
 * Sets and/or provides the value of a setting.
 *
 * @param string $name The name of the setting.
 * @param mixed|null $value The new setting value, null to leave unchanged.
 * @return mixed The setting value.
 */
 public function setting(string $name, $value = null) {

     if ($value !== null) {
        $this->setSettingValue($value);
     }

     $return $this->getSettingValue($name);

 }

The value type of a "setting" can be any primitive type, including the NULL value. Setting the value of the setting "foo" (which e.g. currently has the value 42) to NULL won't work with this method. I've seen and used multiple ways to circumvent this over the years, but is there anything which is considered a best practice here?

Aucun commentaire:

Enregistrer un commentaire