开发者

PHP make class propery inheritable

开发者 https://www.devze.com 2023-01-18 18:05 出处:网络
i have 2 classes A and B that ext开发者_如何学JAVAends A. A has a public property and i want that on the instances of B that property can\'t be accessible. I try to explain better:

i have 2 classes A and B that ext开发者_如何学JAVAends A. A has a public property and i want that on the instances of B that property can't be accessible. I try to explain better:

class A
{
    public $prop;
}
class B extends A
{
    ...
}
$instance=new B;
$instance->prop; //This must throw an error like "Undefined property prop"

I tried with the final keyword but it's only available for methods not for properties. I tried also by setting the same property as private on B but PHP does not allow to change the access level from public to private or protected.

Maybe there's a simple solution to this problem but i can't find it so do you know a way to do this?


Simply change public $prop; to private $prop; by making $prop public you are making it accessible by every possible way, but making it private will make it accessible within a class only


Use magic methods

class A {
    protected $_prop;
    public function __get($key) {   
        if ($key=='prop') {
            return $this->_prop;
        }
    }

    public function __set($key, $value) {
        if ($key=='prop') {
            return $this->_prop = $value;
        }
    }
}

class B extends A {
    public function __get($key) {
    }

    public function __set($key, $value) {
    }

    // how you can use it
    public function foo() {
        echo $this->_prop;
    }
}


Hmm. Tricky!

The only idea that comes to mind is making $prop private from the start, and using magic getter and setter functions to control access. You'd have to store the access information in a separate array and then either return the correct value, or throw a fatal error in the getter function.

0

精彩评论

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

关注公众号