0

I have a somewhat complex search and replace algorithm that uses many different string functions. Rather than peppering my code with things like this:

$mb = true; // use mb functions or not

$len = $mb? mb_strlen($s) : strlen($s);

I'm thinking of doing this, just once:

$_strpos = $mb? 'mb_strpos' : 'strpos';
$_substr = $mb? 'mb_substr' : 'substr';
$_strlen = $mb? 'mb_strlen' : 'strlen';

Then I can use code like this:

$len = $_strlen($s);

It works. The code is much shorter and clearer, and I think it should be faster. Is there any reason not to do this?

4
  • 2
    And why not use mb_ functions always? Commented Jan 14, 2020 at 19:52
  • Totally ok to use higher order functions. Commented Jan 14, 2020 at 19:53
  • Are you doing thousands upon thousands of string manipulations? (I feel your question is Opinion-based. ) Commented Jan 15, 2020 at 1:20
  • I can't use mb_ functions always because some users won't have it installed. In some situations it could be a very large number of string manipulations and using the _mb functions roughly doubles the time to get a response. Commented Jan 17, 2020 at 22:36

1 Answer 1

3

I could think of one main reason: transparency. Neither you nor any future developer nor even your IDE can be 100% certain which function will be called in the end. This is a step towards creating unmaintainable spaghetti code. My advice: don't do it!

What is wrong with using mb_ functions all the time anyway? I only use the other functions if I explicitly need to operate on bytes instead of characters. You as a programmer should know whether you need to perform an action on individual bytes or characters.

If you are worried that the mbstring extension might not be loaded then you can add a check for this in your code.

if (!extension_loaded('mbstring')) {
    throw new \Exception('MBString is not loaded as an extension!');
} 
Sign up to request clarification or add additional context in comments.

2 Comments

The potential reason to not use mb_ functions is the needless overhead. The OP will need to decide whether the extra "effort" is "worth it" and if the user experience is impacted.
This is an excellent point. The program is not part of a larger program so the clarity problem is not huge. I'll have to think about the trade-off with performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.