프로퍼티

클래스 멤버 변수를 속성이라고 합니다. 필드와 같은 다른 용어를 사용하여 참조할 수 있지만 이 참조 속성의 목적을 위해 사용됩니다. 그것들은 선택적으로 PHP 7.4에서 public, protected 또는 private 키워드 중 하나를 사용하여 정의되고, 그 다음에 유형 선언이 오고, 그 다음에 일반 변수 선언이 옵니다. 이 선언에는 초기화가 포함될 수 있지만 이 초기화는 상수 값이어야 합니다.

public, protectedprivate의 의미에 대한 자세한 내용은 가시성을 참조하세요.

메모: PHP 4와의 역호환성을 유지하기 위해 클래스 속성을 선언하는 또 다른 권장되지 않는 방법은 var 키워드를 사용하는 것입니다. 재산을 공개로 선언했을 때와 동일하게 취급합니다.

클래스 메서드 내에서 비정적 속성은 ->(객체 연산자): $this->property(여기서 property은 속성의 이름)를 사용하여 액세스할 수 있습니다. 정적 속성은 ::(이중 콜론): self::$property를 사용하여 액세스합니다. 정적 속성과 비정적 속성의 차이점에 대한 자세한 내용은 Static 키워드를 참조하세요.

의사 변수 $this는 해당 메서드가 개체 컨텍스트 내에서 호출될 때 클래스 메서드 내에서 사용할 수 있습니다. $this는 호출 객체의 값입니다.

예제 #1 속성 선언

                  
<?php
class SimpleClass
{
   public $var1 = 'hello ' . 'world';
   public $var2 = <<<EOD
hello world
EOD;
   public $var3 = 1+2;
   // invalid property declarations:
   public $var4 = self::myStaticMethod();
   public $var5 = $myVar;

   // valid property declarations:
   public $var6 = myConstant;
   public $var7 = [true, false];

   public $var8 = <<<'EOD'
hello world
EOD;
}
?>
                  
                

메모: 클래스와 객체를 처리하는 다양한 기능이 있습니다. 클래스/객체 함수 참조를 참조하세요.


자료형 선언

PHP 7.4.0부터 속성 정의는 callable 예외를 제외하고 Type 선언을 포함할 수 있습니다.

예제 #2 유형이 지정된 속성의 예

                  
<?php

class User
{
    public int $id;
    public ?string $name;

    public function __construct(int $id, ?string $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

$user = new User(1234, null);

var_dump($user->id);
var_dump($user->name);

?>
                  
                

위의 예는 다음을 출력합니다.

int(1234)
NULL
                

형식화된 속성은 액세스하기 전에 초기화해야 합니다. 그렇지 않으면 오류가 발생합니다.

예제 #3 속성 액세스

                  
<?php

class Shape
{
    public int $numberOfSides;
    public string $name;

    public function setNumberOfSides(int $numberOfSides): void
    {
        $this->numberOfSides = $numberOfSides;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }

    public function getNumberOfSides(): int
    {
        return $this->numberOfSides;
    }

    public function getName(): string
    {
        return $this->name;
    }
}

$triangle = new Shape();
$triangle->setName("triangle");
$triangle->setNumberofSides(3);
var_dump($triangle->getName());
var_dump($triangle->getNumberOfSides());

$circle = new Shape();
$circle->setName("circle");
var_dump($circle->getName());
var_dump($circle->getNumberOfSides());
?>
                  
                

위의 예는 다음을 출력합니다.

string(8) "triangle"
int(3)
string(6) "circle"

Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization
                

읽기 전용 속성

PHP 8.1.0부터 속성은 초기화 후 속성 수정을 방지하는 readonly 수정자로 선언될 수 있습니다.

예제 #4 읽기 전용 속성의 예

                  
<?php

class Test {
   public readonly string $prop;

   public function __construct(string $prop) {
       // Legal initialization.
       $this->prop = $prop;
   }
}

$test = new Test("foobar");
// Legal read.
var_dump($test->prop); // string(6) "foobar"

// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>
                  
                

메모: 읽기 전용 수정자는 유형이 지정된 속성에만 적용할 수 있습니다. 유형 제약이 없는 읽기 전용 속성은 혼합 유형을 사용하여 생성할 수 있습니다.

메모: 읽기 전용 static 속성은 지원되지 않습니다.

읽기 전용 속성은 선언된 범위에서만 한 번만 초기화할 수 있습니다. 속성의 다른 할당 또는 수정은 오류 예외를 발생시킵니다.

예제 #5 읽기 전용 속성의 잘못된 초기화

                  
<?php
class Test1 {
    public readonly string $prop;
}

$test1 = new Test1;
// Illegal initialization outside of private scope.
$test1->prop = "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>
                  
                

메모: 읽기 전용 속성에 명시적 기본값을 지정하는 것은 허용되지 않습니다. 기본값이 있는 읽기 전용 속성은 본질적으로 상수와 동일하므로 특별히 유용하지 않기 때문입니다.

                    
  <?php

  class Test {
      // Fatal error: Readonly property Test::$prop cannot have default value
      public readonly int $prop = 42;
  }
  ?>
                    
                  

메모: 읽기 전용 속성은 초기화되면 unset()할 수 없습니다. 그러나 속성이 선언된 범위에서 초기화 전에 읽기 전용 속성을 설정 해제할 수 있습니다.

수정이 반드시 일반 할당은 아니며 다음 모든 경우에도 오류 예외가 발생합니다.

                  
<?php

class Test {
    public function __construct(
        public readonly int $i = 0,
        public readonly array $ary = [],
    ) {}
}

$test = new Test;
$test->i += 1;
$test->i++;
++$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
$ref =& $test->i;
$test->i =& $ref;
byRef($test->i);
foreach ($test as &$prop);
?>
                  
                

그러나 읽기 전용 속성은 내부 변경 가능성을 배제하지 않습니다. 읽기 전용 속성에 저장된 개체(또는 리소스)는 여전히 내부적으로 수정될 수 있습니다.

                  
<?php

class Test {
    public function __construct(public readonly object $obj) {}
}

$test = new Test(new stdClass);
// Legal interior mutation.
$test->obj->foo = 1;
// Illegal reassignment.
$test->obj = new stdClass;
?>