Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

function

php

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

like image 787
Citizen Avatar asked Dec 06 '25 18:12

Citizen


1 Answers

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

?>
like image 150
Robert Greiner Avatar answered Dec 08 '25 08:12

Robert Greiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!