This question already has an answer here:
- Usage of magic strings/numbers [closed] 4 answers
Usually when I code in PHP I try to avoid using literal strings in cases such as:
define('IMAGE_DOWNLOAD_PATH','./data/images/'); define('IMAGE_FILENAME_PREFIX','myapp_'); $ url="http://exaple.com/image.png" function genFilenamesForDownload(string $ url): string { $ extention = pathinfo($ url, PATHINFO_EXTENSION); return IMAGE_DOWNLOAD_PATH.IMAGE_FILENAME_PREFIX.hash('sha512',$ url).".$ {extention}"; }
My rationale behind this is that using constants I make my code more self-documenting and I do not spend time to guess what each literal value is.
But on my experience some developers that I collaborate with find this approach more confusing whilst I find this approach more easy-to-understand especially for new employees or collaborators to the project.
So I wondered which approach is better, to directly use literals or to define my literals as constants? Also is this approach good for all cases?