-2

In PHP there does not seem to be a big disparity between private and protected methods.

I asked why I should use protected in PHP Chatroom and got this answer:

unless you have good reason not to : yes
and good reason is , if you code is closed-source library
and even then , it can be overridden with reflections

So --

If the private method could potentially be overridden with Reflections, what is the point at all in private methods?

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303

3 Answers3

9

private and protected are there to make it easier to write code that does the right thing. As you've noticed, they're not unbreakable -- there's nothing preventing you from bypassing them if you want to. That's because they're meant to protect you from accidentally doing the wrong thing, not from actively trying to.

That you can bypass them with reflection, doesn't mean you should. You can consider private and protected as kinda a "warranty void if broken" sticker; if you ignore them and muck around with stuff yourself directly, the object/class might not behave properly. It has no obligation to at that point, since you've taken it upon yourself to mess with its innards -- and the code that does so is entirely to blame.

Now, as for the question in the title...you use protected to declare the interface specifically for subclasses; you basically declare that you intend for them to use that stuff directly, while private says that you don't. Whether they disregard that is up to them, but if they do, then screw 'em. You tried to warn them.

cHao
  • 84,970
  • 20
  • 145
  • 172
1

Yes it can be overridden using reflection but that's not the point, the point is to restrict access to the method under normal use, i.e. if someone is using your class they shouldn't be able to access that method because it violates the contract that class has.

It's private/protected depending on the use of it, so if someone has made a method private then they've done it because you shouldn't need to access it from another class, if they've made it protected then likely they only intended sub classes to be able to access the method.

James Goodwin
  • 7,360
  • 5
  • 29
  • 41
-1
class GrandPa
{
    private $name = 'Mark Henry';

    function getName(){
        return $this->name;
    }
}

class Daddy extends GrandPa
{
    function displayGrandPaName()
    {
        return $this->name;
    }


}

$daddy = new Daddy;

echo $daddy->getName(); // work
echo $daddy->displayGrandPaName(); // Error Undefined property: 

Try change private $name = 'Mark Henry'; to protected

zloctb
  • 10,592
  • 8
  • 70
  • 89