Nice programing

리플렉션 클래스를 사용하여 개인 / 보호 정적 속성을 설정하는 방법이 있습니까?

nicepro 2020. 12. 11. 19:25
반응형

리플렉션 클래스를 사용하여 개인 / 보호 정적 속성을 설정하는 방법이 있습니까?


클래스의 정적 속성에 대한 백업 / 복원 기능을 수행하려고합니다. 리플렉션 개체 getStaticProperties()메서드를 사용하여 모든 정적 속성 및 해당 값 목록을 가져올 수 있습니다 . 이것은 privatepublic static속성과 그 값을 모두 얻습니다 .

문제는 반사 객체 setStaticPropertyValue($key, $value)메서드로 속성을 복원하려고 할 때 동일한 결과를 얻지 못하는 것 같습니다 . privateprotected변수는 그대로이 메서드에 표시되지 않습니다 getStaticProperties(). 일관성이없는 것 같습니다.

리플렉션 클래스를 사용하여 개인 / 보호 된 정적 속성을 설정하는 방법이 있습니까, 아니면 그 문제에 대한 다른 방법이 있습니까?

시도

class Foo {
    static public $test1 = 1;
    static protected $test2 = 2;

    public function test () {
        echo self::$test1 . '<br>';
        echo self::$test2 . '<br><br>';
    }

    public function change () {
        self::$test1 = 3;
        self::$test2 = 4;
    }
}

$test = new foo();
$test->test();

// Backup
$test2 = new ReflectionObject($test);
$backup = $test2->getStaticProperties();

$test->change();

// Restore
foreach ($backup as $key => $value) {
    $property = $test2->getProperty($key);
    $property->setAccessible(true);
    $test2->setStaticPropertyValue($key, $value);
}

$test->test();

클래스의 private / protected 속성에 액세스하려면 먼저 리플렉션을 사용하여 해당 클래스의 액세스 가능성을 설정해야 할 수 있습니다. 다음 코드를 시도하십시오.

$obj         = new ClassName();
$refObject   = new ReflectionObject( $obj );
$refProperty = $refObject->getProperty( 'property' );
$refProperty->setAccessible( true );
$refProperty->setValue(null, 'new value');

ReflectionObject인스턴스 없이 리플렉션을 사용하여 클래스의 개인 / 보호 된 속성에 액세스하려면 :

정적 속성의 경우 :

<?php
$reflection = new \ReflectionProperty('ClassName', 'propertyName');
$reflection->setAccessible(true);
$reflection->setValue(null, 'new property value');


비 정적 속성의 경우 :

<?php
$instance = New SomeClassName();
$reflection = new \ReflectionProperty(get_class($instance), 'propertyName');
$reflection->setAccessible(true);
$reflection->setValue($instance, 'new property value');

참고 URL : https://stackoverflow.com/questions/6448551/is-there-any-way-to-set-a-private-protected-static-property-using-reflection-cla

반응형