[php] 따옴표(')와 쌍따옴표,큰따옴표(")의 차이

안녕하세요. 개발자 드리머즈입니다.


php에서 따옴표(')(single quotation mark)와 큰따옴표(")(double quotation mark)가 어떻게 다른지 찾아봤습니다.



출처 :

https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php

  1. Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed).
  2. Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you what to echo "The $types are" That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such. 


해석

1. 홑따옴표로 둘러싸인 문자열은 그 내용을 거의 "그대로" 보여줍니다. 변수와 대부분의 이스케이프 시퀀스는 변형되지 않을 것입니다. 예외 경우는, 말 그대로 홑따옴표를 나타내기 위해 백슬래쉬와 함께 사용(\')해야 하고, 백슬래쉬를 보여주기 위해서는 또다른 백슬래쉬와 함께 사용(\\)해야 한다는 것입니다. (네. 심지어 홑따옴표도 변형이 됩니다)

2. 큰따옴표로 둘러싸인 문자열은 (정규식 일부를 포함하여) 이스케이프 문자의 host를 보여줄 것이고, 문자열 안의 변수들은 변수값으로 변형될 것입니다. 여기서 중요한 점은 변형되길 원하는 변수를 중괄호를 사용하여 명확하게 표시할 수 있다는 것입니다. 예를 들어서 $type 이라는 변수가 있고 echo "The $types are"라고 표현하고 싶지만 $types 변수로 보이는 경우가 있습니다. 이를 해결하기 위해 echo "The {$type}s are"를 사용하세요. 왼쪽 중괄호는 달러 표시 전이나 후에 넣으면 됩니다. 배열 변수와 같은 것들에 대한 사용법을 알기 위해 string parsing을 보세요.


그렇다고 합니다.


$name = 'Mike';

 No.

 테스트 코드

결과 

 1(홑따옴표)

 echo '$name is \n a student';

 $name is \n a student

 2(쌍따옴표)

 echo "$name is \n a student";

 Mike is a student

 3(쌍따옴표)

 echo "$nameis \n a student";

 a student

 4(쌍따옴표)

 echo "{$name}is \n a student"; Mikeis a student


위와 같이 테스트를 해봤습니다.

1번의 결과를 보시면 알겠지만.. 홑따옴표로 둘러싸인 문자열은 변형없이 그대로 출력됩니다. (홑따옴표와 백슬래쉬는 예외)

2,3,4번은 같이 보겠습니다.

2번과 같이 $name이 다른 단어와 붙어있지 않다면 중괄호 없이 써도, $name의 값(Mike)으로 변형되어 보여집니다.

그러나 3번과 같이 $name이 다른 단어(is)와 붙어있다면 $nameis를 하나의 변수로 인식하여 문제가 생깁니다.

그래서 이런 경우에는 변수를 중괄호로 감싸서 확실하게 표현해야 합니다.

쌍따옴표 안의 변수를 나타낼 때 중괄호를 항상 써야하는 건 아니지만.. 쓰는 습관을 들이는게 좋을 것 같습니다.

그리고 2,3,4번의 결과에서 제대로 안보이지만.. 개행문자(\n)는 1번처럼 그대로 보이지 않고 줄 바꿈 동작을 했습니다. 다만 HTML 코드에서 그냥 개행 문자를 쓰면.. 줄 바뀜이 무시되서 그렇습니다.



작성자

Posted by 드리머즈

관련 글

댓글 영역