开发者

Is there any way to reset all static properties of a particular class?

开发者 https://www.devze.com 2023-03-14 15:53 出处:网络
Static properties make testing hard as you probably know. Is there no way to reset all static properties of a particular class back to their initial state? Ideally this would not require custom code f

Static properties make testing hard as you probably know. Is there no way to reset all static properties of a particular class back to their initial state? Ideally this would not require custom code for each class, but could be used in a general way by inheritance, or from outside of the class completely.

Please do not reply with something like, "don't use static properties开发者_C百科". Thanks.


Assuming you're using PHPUnit:

See the PHPUnit Manual section about global state. Static members are covered by this if you have PHP 5.3 or higher. Static members are not part of serialization (in case you wonder).

See as well @backupGlobals and @backupStaticAttributes


No. PHP does not preserve that information.

I was toying around with ReflectionClass and ::getDefaultProperties and ::getStaticProperties, but they only return the current state.

You will have to create an array with the default values, then manually foreach over them and reset your class attributes.


I couldn't find any way to include or require classes or functions many times without getting an error.

Anyway, if you need to replace functions inside an structure you should make an array/ArrayObject of lamdas/inline functions (like javascript objects)

When you re import the array it will back to the original state.

$Animal = array(
    'eat' => function($food) {/*...*/},
    'run' => function($to_place) {/*...*/}
);
$Animal['eat'] = function($food) {/* new way to eat */}

I also managed to reset the state of static attributes by using Reflections. For this approach you need to use a convention attribute naming for default value of each type.

class MyStaticHolder {
    public static $x_array = array();
    public static $x_num = 0;
    public static $x_str = '';
}

//change values
MyStaticHolder::$x_array = array(1,2,4);
MyStaticHolder::$x_num = -1.4;
MyStaticHolder::$x_str = 'sample-text';

function reset_static($class_name) {
    $z = new ReflectionClass($class_name);
    $properties = $z->getDefaultProperties();
    print_r($properties);
    foreach ($properties as $property_name => $value) {
        $sufix = end(explode('_',$property_name));
        switch ($sufix) {
            case 'array':
                $class_name::$$property_name = array();
                break;
            case 'num':
                $class_name::$$property_name = 0;
                break;
            case 'str':
                $class_name::$$property_name = '';
                break;
            default:
                $class_name::$$property_name = null;
                break;
        }
    }
}

reset_static('MyStaticHolder');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号