Taking advantage of the @elias hook, if non-existence of constants is somewhat serious in your application, a more consistent alternative to returning error messages in functions is to use exceptions, like this:
if (empty($dump))
throw new Exception("Atenção: Não foram localizadas constantes com o prefixo '".$prefix."'");
However, if it is just informative, log the message and return an empty list.
Also, consider the principle of single responsibility and, depending on the use of this message, put this if
into the "client" code, which calls the method. Here's an example:
define('CON_WEBSITE_01', 'John');
(...)
$constants = get_constantsByPrefix('CON_WEBSITE_');
print_r( empty($constants) ? "Nada encontrado" : $constants );
Regarding the performance of the get_constantsByPrefix()
function, depending on the use case, we can consider the following factors:
Can constants be defined in the middle of the main system execution, or are they usually set at startup, for example, by adding classes at the beginning of the script?
Depending on the case, it would be worth storing the return map for later use, rather than always iterating over all constants.
Let's scribble an example using a class:
class Constants {
private $constant_map = null;
public static function listByPrefix($prefix) {
if ($this->constant_map == null) {
$this->constant_map = array();
foreach (get_defined_constants() as $key=>$value) {
if (substr($key,0,strlen($prefix))==$prefix) {
$this->constant_map[$key] = $value;
}
}
}
if (empty($this->constant_map)) {
throw new Exception("Atenção: Não foram localizadas constantes com o prefixo '".$prefix."'");
} else {
return $this->constant_map;
}
}
}
Example usage:
define('CON_WEBSITE_01', 'John');
Constants::listByPrefix('CON_WEBSITE_');
Do you have control over setting constants?
In this case, you could encapsulate creating them with a function that already stores them on the map.
Another sketch:
class Constants {
private $constant_map = array();
public static function define($key, $value) {
define($key);
$this->constant_map[$key] = $value;
}
public static function listByPrefix($prefix) {
if (empty($this->constant_map)) {
throw new Exception("Atenção: Não foram localizadas constantes com o prefixo '".$prefix."'");
} else {
return $this->constant_map;
}
}
}
Example usage:
Constants::define('CON_WEBSITE_01', 'John');
Constants::listByPrefix('CON_WEBSITE_');