Public, protected and private access modifiers in PHP

Updated

The visibility of a property, a method in php 7.1.0 of a constant can be defined by adding a prefix in the declaration. These prefix are the keywords public, protected or private. Public class members can be accessed everywhere. Protected members can be accessed only within the class itself and also by inheriting the parent classes. Private members may only be accessed by the class that defines the member. Now we can see examples of these access modifiers

<?php
/**
 * Define MyClass
 */
class MyClass {
    public $public = 'PUBLIC';
    protected $protected = 'PROTECTED';
    private $private = 'PRIVATE';

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

$obj = new MyClass();
echo $obj->public; 
echo $obj->protected; 
echo $obj->private; 
$obj->printMessage(); 


/**
 * Define MyClass1
 */
class MyClass1 extends MyClass
{
    // We can redeclare the public and protected properties, but not private
    public $public = 'PUBLIC1';
    protected $protected = 'PROTECTED1';

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

$obj2 = new MyClass1();
echo $obj2->public; 
echo $obj2->protected;
echo $obj2->private; 
$obj2->printHello(); 
?>
works
Fatal error
Fatal error
PUBLIC, PROTECTED and PRIVATE

works
Fatal error
Undefined
PUBLIC1, PROTECTED1 and Undefined
Comment
Mithlesh Upadhyay Published 1 Dec 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials