views:

41

answers:

3

Hi, i have 2 classes A and B that extends 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?

A: 

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.

Pekka
+1  A: 

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;
    }
}
how
+2  A: 

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

mrNepal
I was looking for a way to preserve the property on the base class, but maybe there's no other way.
mck89