Home > OS >  Private property accessibility confusion
Private property accessibility confusion

Time:08-25

I am now really confused about the following:

class A {
    
    public function setPropertyValue($prop, $val) {
        $this->$prop = $val;
    }
    
}

class B extends A {
    
    private $foo;
    
}

$obj = new B();
$obj->setPropertyValue("foo", "whatever"); // Fatal error: Uncaught Error: Cannot access private property B::$foo

Why and what is the point of not being able to access the private property since it is a property of B object that was instantiated and that the method is called on?

The error would make sense if it were the other way around: $foo being a private property of A and therefore not visible through inheritance to B.

I just cannot figure out why would this behavior be useful.

CodePudding user response:

Per OOP principles:

The visibility of a property, a method or a constant can be defined by prefixing the declaration with the keywords public, protected or private.

  • Class members declared public can be accessed everywhere.
  • Members declared protected can be accessed only within the class itself and by inheriting and parent classes.
  • Members declared as private may only be accessed by the class that defines the member.

CodePudding user response:

Private is only for the class instance using it. If you want to make it available for child or parent classes, but keep it unavailabe for public, make it protected.

class A
{

    public function setPropertyValue($prop, $val)
    {
        $this->$prop = $val;
    }

}

class B extends A
{
    protected $foo;
}

$obj = new B();
$obj->setPropertyValue("foo", "whatever");

CodePudding user response:

private - the property or method can ONLY be accessed within the class

You can't access or set a private property from anywhere else except the class it is created.

The only way of working with a private property in a class is by modyfying it in a public method of the same class.

  • Related