Is there any way to set a private/protected static property using reflection classes?

后端 未结 2 1411
广开言路
广开言路 2020-12-24 00:31

I am trying to perform a backup/restore function for static properties of classes. I can get a list of all of the static properties and their values using the reflection obj

相关标签:
2条回答
  • 2020-12-24 00:58

    For accessing private/protected properties of a class we may need to set the accessibility of that class first, using reflection. Try the following code:

    $obj         = new ClassName();
    $refObject   = new ReflectionObject( $obj );
    $refProperty = $refObject->getProperty( 'property' );
    $refProperty->setAccessible( true );
    $refProperty->setValue(null, 'new value');
    
    0 讨论(0)
  • 2020-12-24 01:05

    For accessing private/protected properties of a class, using reflection, without the need for a ReflectionObject instance:

    For static properties:

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


    For non-static properties:

    <?php
    $instance = new SomeClassName();
    $reflection = new \ReflectionProperty(get_class($instance), 'propertyName');
    $reflection->setAccessible(true);
    $reflection->setValue($instance, 'new property value');
    
    0 讨论(0)
提交回复
热议问题