Citizen
Citizen

Reputation: 12927

From a usage standpoint, what's the difference between a private and protection class function?

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

Upvotes: 3

Views: 254

Answers (2)

dfilkovi
dfilkovi

Reputation: 3081

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.

Upvotes: 2

Robert Greiner
Robert Greiner

Reputation: 29722

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

?>

Upvotes: 3

Related Questions