
❯ php -a Interactive shell php > $name = 'foo'; php > echo 'Hello $name. $name, you have 10 unread messages'; Hello $name. $name, you have 10 unread messages php > echo "Hello $name. $name, you have 10 unread messages"; Hello foo. foo, you have 10 unread messages php >
위 구문에서 작은 따옴표와 큰 따옴표의 차이를 주목해 보자. 큰 따옴표만 문자열 끼워 넣기를 할 수 있다. 하지만 이 용법은 모범 사례가 아니다.
아래 예제가 올바른 문법이다.
php > echo 'Hello '.$name.'. '.$name.', you have 10 unread messages'; Hello foo. foo, you have 10 unread messages php > echo "Hello {$name}. {$name}, you have 10 unread messages"; Hello foo. foo, you have 10 unread messages php >
먼저 작은 따옴표를 사용하는 경우, 따옴표 밖에 있는 점(.) 즉 PHP 의 문자열 결합 연산자를 통해서만 문자열과 변수를 결합할 수 있다.
큰 따옴표를 쓰는 경우에는 PHP 문자열 결합 연산자(.)를 사용하지 않고 문자열 안에 변수를 끼워 넣을 수 있지만, 위 예제와 같이 변수명을 중괄호({}
)로 감싸는 것이 좋다. 그 이유는 “$nameyou can..”과 같이 인접 문자열과 변수가 구분되지 않을 때를 위해서이다.
“[PHP] 변수의 값을 문자열에 끼워 넣기”에 대한 1개의 생각