tags:

views:

40

answers:

2

I know the manual definition, but from a real life usage standpoint, what's the difference? When would you use one over the other?

+1  A: 

EDIT: use protected methods when you want a child class (one that extends your current (or parent) class) to be able to access methods or variables within the parent.

Here is the PHP Visibility Manual

private can be seen by no other classes except the one the variable/method is contained in.

protected can be seen by any class that is in the same package/namespace.

Code from the manual.

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined

?>
Robert Greiner
When would you want to use one over the other?
Citizen
@Citizen, see edits
Robert Greiner
The other answer answered what I was looking for but I also found your post informative. I upvoted!
Citizen
cool, I'm glad you got your question answered.
Robert Greiner
+1  A: 

When you know that a variable will be used only in that class and not in any other or extending class you would name it private. So if you extend the class and mistakenly name the variable as the name of a private this would give you error and thus prevent you from making mistakes.

If you for example use many pages in your web application and all of the pages are classes that extend one single class that handles header and footer of the page (cause it's always the same) you can override for example the default title of the page which is set up in parent class with protected variable setting.

I hope this helps.

dfilkovi