微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-通过方法重置类实例变量

有谁知道如何通过类方法重置实例变量.像这样:

class someClass 
{
    var $var1 = '';
    var $var2 = TRUE;

    function someMethod() 
    { 
        [...]
        // this method will alter the class variables
    }

    function reset()
    {
        // is it possible to reset all class variables from here?
    }
}

$test = new someClass();
$test->someMethod();
echo $test->var1;

$test->reset();
$test->someMethod();

我知道我可以简单地执行$test2 = new SomeClass()但我特别在寻找一种通过方法重置实例(及其变量)的方法.

这有可能吗???

解决方法:

您可以使用反射来实现此目的,例如使用get_class_vars:

foreach (get_class_vars(get_class($this)) as $name => $default) 
  $this -> $name = $default;

这并不完全可靠,它会中断非公共变量(get_class_vars无法读取),并且不会接触基类变量.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐