문제 설명
클래스 상수를 사용한 PHP 객체 액세스 (PHP Object access with class constant)
PHP에서 멤버 이름이 클래스 상수로 지정된 개체의 멤버에 액세스할 수 있습니까?
다음 예를 살펴보세요.
class X{
const foo = "abc";
}
class Y{
public $abc;
}
$y = new Y();
$y‑>X::foo = 23; //This does not work
파서는 마지막 줄을 수락하지 않지만 이것이 내가 원하는 것입니다. 클래스 상수 X::foo
에 저장된 이름으로 필드에 액세스하고 싶습니다. 이를 달성하는 구문이 있습니까?
참조 솔루션
방법 1:
Use variable variables, either via a temp or directly:
$name = X::foo; // Via temp var
$y‑>$name = 23; // Access the member by the string's content
var_dump($y‑>{X::foo}); // Dumps 23
방법 2:
You should write your code like this
$y‑>{X::foo} = 23;
Hope it helps
(by gexicide、Niels Keurentjes、php‑dev)