Question

I want to use property look-up on an associative array of strings, but there's a catch - I need to be able to use a variable in the string. I came up with two solutions, but both seem hacky in PHP.

$foo = [
  'someProp' => 'Some value here: $$value$$.'
];
$myProp = 'someProp';
$value = 'some value';
$myString = $foo[$myProp];
$myString = str_replace('$$value$$', $value, $myString);
echo $myString;

In JavaScript, I would probably use functions instead of strings and return the string including the variable. I've heard that this is bad practice in PHP.

$foo = array(
  'someProp' => function($value) {
    return "Some value here: {$value}.";
  }
);
$myProp = 'someProp';
$value = 'some value';
$myString = $foo[$myProp]($value);
echo $myString;

To be sure this is not an X/Y problem, I will say that my goal is to abstract my error messages to one location in my code (the array mentioned here) and form what might be considered an error api for use throughout the application. For example:

try {
  something(); //throws "MyException('someProp', 'someValue');
}
catch (MyException $e) {
  $someClass->addError($e->getType(), $e->getValue());
  //this function will get the string based on $type and add $value to it, then add the message to an array
}

Are either of these two approaches the way to go? The answer I'm looking for would include a more optimum solution if there is one and mature thoughts on my two proposed solutions.

Was it helpful?

Solution

From your example, is there only a single variable per message string or it could be many variables?

If there's only single variable, instead of role out your old string interpolation, you could use sprinf for this. This is more flexible in my opinion since it allows you to do many formatting types e.g. int, decimal etc

$foo = [
   'someProp' => 'Some value here: %s.'
];
$myString = sprintf($myString, $value);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top