Why a full stop, “.” and not a plus symbol, “+”, for string concatenation in PHP?

前端 未结 12 1629
暖寄归人
暖寄归人 2020-12-09 01:54

Why did the designers of PHP decide to use a full stop / period / \".\" as the string concatenation operator rather than the more usual plus symbol \"+\" ?

Is there

12条回答
  •  长情又很酷
    2020-12-09 02:25

    While this isn't the historical reason it maybe show you why it is good to have a separate operator for addition and concatenation in the case of PHP.

    The reason is what we see in JavaScript. We use the + character for concatenation and addition too. In PHP we have a separate operator for the two which is important for dynamically typed languages where implicit type conversion also present.

    In PHP

    echo  5  + 1; //6
    echo  5  . 1; //51
    echo "5" + 1; //6
    echo "5" . 1; //51
    

    This isn't surprising for anyone because we always explicitly stated whether we want to add or concatenate the two variable. Or in other words if we think about them as numbers or as strings.

    In JavaScript

    console.log( 5  +  1);  //6
    console.log("5" +  1);  //51
    console.log( 5  + "1"); //51
    console.log("5" + "1"); //51
    

    Without the knowledge of how implicit type conversions happen under the hood, in many cases (especially if they are complex) surprising results can happen, because we don't know what will be the outcome, because it isn't explicitly stated.

    In Python

    Python also uses the + operator for concatenation and for addition too, but it doesn't let implicit type conversion to happen. You have to explicitly mark the type conversion.

    print  5  + 1 //6
    print "5" + 1 //TypeError: cannot concatenate 'str' and 'int' objects
    

    We have to do type conversion to make it work: a + int(b)

    All in all

    If we think about it, we can see that almost the same thing happens in PHP what we see in Python but instead of explicitly marking the type conversion, we mark with the operator that how we see the variables in terms of types.

提交回复
热议问题