On 03/01/2020 18:55, Mike Schinkel wrote:
So for five data elements, 5 easy to read lines of code with constants vs. 20 
harder to read lines with functions, or at least 40 lines if we include PHPDoc 
for those functions, which is part of our standard for writing functions.


This is, as so often with such comparisons, an exaggeration: the docblock for a function need not be any longer than the docblock for a constant, and the function body can be simplified.

For the initial hard-coded state, we have 2 lines per constant vs 4 per method:

/** @var string The base URL of the API */
public const BASE_URL = 'http://api.example.com';

vs

/**@return string The base URL of the API */
public static function getBaseUrl() {
    return 'http://api.example.com';
}


Add in the "initialise on first read", and you end up with 4 lines per pseudo-constant vs 5 per method:

/** @var string The base URL of the API */
public const BASE_URL:string {
      return Config::get_options('api_base_url');
}

vs

/**@return string The base URL of the API */
public static function getBaseUrl() {
    static $baseUrl;
    return $baseUrl ??= Config::get_options('api_base_url');
}


Overall, I agree with Larry that these aren't really constants, and shouldn't be treated as such. Property accessors, or some native support for lazy-loading properties (which would stop Doctrine needing to do tricks with unset() and __get), would seem like a better fit for the use case.

Something like:

public static string $baseUrl {
    readonly,
    get => $this->baseUrl ??= Config::get_options('api_base_url')
}

or:

public static string $baseUrl {
    readonly,
    lazy-load => Config::get_options('api_base_url')
}

Regards,

--
Rowan Tommins (né Collins)
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to