Emulate public/private properties with __get() and __set()?

流过昼夜 提交于 2019-12-04 16:28:46
Artefacto

Is there a way I can emulate public and private properties in a php class that uses __get() and __set()?

Not directly (if you discount debug_backtrace).

But you can have a private method getPriv that does all the work your current __get does. Then __get would only wrap this private method and check accessibility.

function __get($name) {        
    if (in_array($name, $this->privateProperties))
        throw new Exception("The property ". __CLASS__ . "::$name is private.");
    return $this->getPriv($name);
}

Inside your class, you would call getPriv, thus bypassing __get.

Make abstraction::$arrPropertyValues protected or do what Artefacto wrote (if you need additional checks), except that abstraction::getPriv() should be protected.

Rather than manually enlisting private/protected properties, you could use PHPs cumbersome reflection methods:

function __get($name) {

    $reflect = new ReflectionObject($this);
    $publics = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);

    if (in_array($name, $publics)) {
         return $this->{$name};
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!