[php] PHP에서 문자열의 중괄호

{ }PHP에서 문자열 리터럴에서 (중괄호) 의 의미는 무엇입니까 ?



답변

이것은 문자열 보간을위한 복잡한 (곱슬 한) 구문 입니다. 매뉴얼에서 :

복잡한 (곱슬 한) 구문

구문이 복잡하기 때문에 복잡한 식을 사용할 수 없기 때문에 복잡하지 않습니다.

문자열 표현이있는 스칼라 변수, 배열 요소 또는 객체 속성은이 구문을 통해 포함될 수 있습니다. 이 문자열 바깥에 표시하는 것처럼 간단하게 표현 같은 방법을 쓰고, 그 다음에 그것을 포장 {하고 }. 이후 {때 탈출 할 수없는,이 구문 만 인식됩니다 $즉시이 다음 {. {\$리터럴을 얻는 데 사용
합니다 {$. 명확하게하는 몇 가지 예 :

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

종종이 구문은 불필요합니다. 예를 들면 다음과 같습니다.

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

다음과 정확히 동일하게 작동합니다.

$out = "{$a} {$a}"; // same

따라서 중괄호는 필요하지 않습니다. 그러나 이것은 :

$out = "$aefgh";

이름 $aefgh에 변수가 없으므로 오류 수준에 따라 작동하지 않거나 오류가 발생하므로 다음 을 수행해야합니다.

$out = "${a}efgh"; // or
$out = "{$a}efgh";


답변

저에게 중괄호는 연결을 대체하는 역할을하며 입력하기 가 더 빠르며 코드가 더 깨끗해 보입니다. 작은 따옴표 ( ”) 로 변수 의 리터럴 이름 을 얻을 수 있으므로 PHP에서 내용을 구문 분석 할 때 큰 따옴표 ( “”)를 사용해야합니다 .

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>


답변

예:

$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";

중괄호가 없으면 PHP는 $numberth존재하지 않는 변수를 찾으려고 시도 합니다!


답변

또한 속성 이름이 일부 반복자에 따라 다른 객체 속성에 액세스하는 것이 유용하다는 것을 알았습니다. 예를 들어, 시간, 일, 월의 기간에 대해 아래 패턴을 사용했습니다.

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

이 동일한 패턴을 사용하여 클래스 메소드에 액세스 할 수도 있습니다. 문자열과 문자열 변수를 사용하여 동일한 방식으로 메소드 이름을 빌드하십시오.

기간별로 가치 저장을 위해 배열을 사용한다고 쉽게 주장 할 수 있습니다. 이 응용 프로그램이 PHP 전용이라면 동의합니다. 클래스 속성이 데이터베이스 테이블의 필드에 매핑 될 때이 패턴을 사용합니다. 직렬화를 사용하여 데이터베이스에 배열을 저장할 수는 있지만 개별 필드를 색인화해야하는 경우 비효율적이며 의미가 없습니다. 필자는 종종 반복자에 의해 키가 지정된 필드 이름 배열을 두 세계 모두를 위해 추가합니다.

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}


답변

여기 하나의 워드 프레스 플러그인에서 얻은 코드가 있습니다.

$data = $wpdb->get_results("select * from {$wpdb->prefix}download_monitor_files");

이것은 복잡한 문자열을 형식화하는 데 정말 편리한 기술입니다.


답변