아마 당신은 할 수있는 최선의 마법 게터/세터 메소드 및 속성의 배열을 사용할 수 있습니다 : 속성이 개인 것을
<?php
abstract class Z
{
private $properties = array();
function __construct()
{
$x = get_called_class();
$this->$x = null;
}
public function __set($prop, $val)
{
$this->properties[$prop] = $val;
}
public function __get($prop)
{
return $this->properties[$prop];
}
}
class A extends Z
{
}
var_dump(new A());
참고, 아이 클래스는 __get
및 __set
방법을 통해 이동해야합니다.
동적 속성을 호출 된 클래스 이름으로 제한 할 수도 있습니다.
<?php
abstract class Z
{
private $classprop;
function __construct()
{
$x = get_called_class();
$this->$x = true;
}
public function __set($prop, $val)
{
if ($prop !== get_called_class()) {
throw new \UnexpectedValueException('Cannot Set Dynamic properties Other than Class Name');
}
$this->classprop = $val;
}
public function __get($prop)
{
if ($prop !== get_called_class()) {
throw new \UnexpectedValueException('Cannot Get Dynamic properties Other than Class Name');
}
return $this->classprop;
}
}
class A extends Z
{
}
왜 이런 동적 속성이 필요한지 신중하게 생각해보십시오.
다음과 같이 표시됩니다. 'object (A) # 1 (0) {}'어떻게하면 obj를 만들 수 있습니까? – Rizier123