[Solved] Why do i have to create another method to access a protected method from a parent class?


Basic OOP access restrictions are made for encapsulation.

Public access – allows access from anywhere (outside/inside).

Protected access – allows access from inside class itself or the class that inherits(child class).

Private access – allows access only WITHIN class, not child

In additional, to deeply understand what is OOP and follow the GOOD HABBITS for OOP from the beginning – I suggest you to read SOLID, the five first oop principles. They are the KEY to the OOP Approach. Read and understand these.
You may also want to read GRASP OOD Principles.
There is also a common accepted coding standards around – PEAR Coding Standard

Public example

Class A {
  public $a = "hello oop world";
  public function getA()
  {
    return $this->a;
  }
}
# call successful in any case
$a = new A;
$a->getA(); // success
echo $a->a // success due to it's access public

Protected Example

Class A {
  public $a = "hello OOP world";
  protected $_b = "Here we test protected";
  public function getA() {
    return $this->a;
  }
}

Class B extends A {
  public function getB() {
    return $this->_b;
  }
}

# test
$a = new A; #init
$b = new B; #init
echo $a->a; // success - prints "hello oop world"
echo $a->_b; // fails with access error.
echo $a->getA(); // success print hello oop world
echo $b->getA(); // also prints hello oop world (inherited all of the parent class!)
echo $b->getB(); // return the $_b ! why? it is inherited and we made public getter in child class!

Private example

Class A {
  private $_sharedProperty = "Sometimes Private is good!"
  public function parentGetter() {
    return $this->_sharedProperty;
  }
}

Class B {
  public childGetter() {
    return $this->_sharedProperty;
  }
}

# Now we test, as we can see, both methods trying to access shared property.
$parent = new A; #instantiate
$child = new B; #instatiate
echo $parent->_sharedProperty; // Fails with access restricted.
echo $parent->parentGetter(); // print the shared property of instance.
echo $child->_sharedProperty   // Fails also with access restricted.
echo $child->childGetter(); // FAILS ! Why? Private is not available to child!

Hope this helps.

Regards,

VR

solved Why do i have to create another method to access a protected method from a parent class?