What is the difference between public, private, and protected ?

What is the difference between public, private, and protected php7

What is the difference between public, private, and protected ?



What is the difference between public, private, and protected ?

In Object oriented programming we can define visibility as public, protected, private. So





Public variables can be used inside or outside of the class. Whereas Protected and Private variables cannot be used outside of class.



The deference between Protected and private Visibility.





Private variable can be used inside of class where that variable is defined. we cannot use Private variable outside of class or in child class whereas Protected variable can be used inside of class and inside child class also but not out side of main and child class.



<?php

class User{
    // Public variable
    public $name = 'Manu';
    public $age = '23';
    // Protected variable
    protected $userId = '3345dwr';
    //Private variable
    private $balance = '4564';

    // Public Functions
    public function userDetails(){
        // function calling protected variable
        return $this->userId;
    }

    public function balanceCheck(){
        // function calling private variable
        return $this->balance;
    }
}

// Child class 
class employee extends User{
    // Public function 
    public function displayDetails(){
        // Function calling parent class protected variable
        return $this->userId;
    }
}


//Creating Object of User class
$user = new User();

//Creating Object of child class
$employee = new employee();

//Will display us Protected variable printed
echo $employee->displayDetails();

// Will display User name as it is public
echo $user->name;


// Will not display User userId as it is protected
echo $user->userId;

// Will not display User balance as it is private
echo $user->balance;