Hypothetical concatenation predicament

荒凉一梦 提交于 2019-12-04 14:06:56

Does it have to be one character? .. could work!

Any myriad of combinations, like ~~ or >: even!

If you don't want to use + or ., then I would recommend ^ because that's used in some other languages for string concatenation and I don't believe that it's used for anything in PHP. Edit: It's been pointed out that it's used for XOR. One option would be to use ^ anyway since bitwise XOR is not commonly used and then to map something else like ^^ to XOR. Another option would be to use .. for concatenation. The problem is that the single characters are mostly taken.

Another option would be to use +, but map it to a function which concatenates when one argument is a string and adds otherwise. In order to not break things which rely on strings which are numbers being treated as their values, we should probably treat numeric strings as numbers for these purposes. Here's the function that I would use.

function smart_add($arg1,$arg2) {
    if ($arg1.is_numeric() && $arg2.is_numeric()) {
        return $arg1 + $arg2;
    } else {
        return $arg1 . $arg2;
    }
}

Then a + b + c + d just gets turned into smart_add(smart_add(smart_add(a,b),c),d)

This may not be perfect in all cases, but it should work pretty well most of the time and has clear rules for use.

So my question is: If I was to decide to introduce a new method of string concatenation, what character would make the most sense?

As you're well aware of, you'll need to chose a character that is not being used as one of PHP's operators. Since string concatenation is a common technique, I would try to avoid using characters that you need to press SHIFT to type, as those characters will be a hindrance.

Instead of trying to assign one character for string concatenation (as most are already in use), perhaps you should define your own syntax for string concatenation (or any other operation you need to overwrite with a different operator), as a shorthand operator (sort of). Something like:

[$string, $string]

Should be easy to pick up by a parser and form the resulting concatenated string.

Edit: I should also note that whether you're using literal strings or variables, there's no way (as far as I know) to confuse this syntax with any other PHP functionality, since the comma in the middle is invalid for array manipulations. So, all of the following would still be recognized as string concatenation and not something else in PHP.

["stack", "overflow"]
["stack", $overflow]
[$stack, $overflow]

Edit: Since this conflicts to JSON notation, the following alternative variations exist:

  1. Changing the delimiter
  2. Omitting the delimiter

Example:

[$stack $overflow $string $concatenation] // Use nothing (but really need space)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!