0
0
PHPprogramming~5 mins

Properties and visibility in PHP

Choose your learning style9 modes available
Introduction

Properties store information inside an object. Visibility controls who can see or change these properties.

When you want to keep some data inside an object private and safe.
When you want to allow other parts of the program to read but not change a value.
When you want to share some information freely with any code.
When you want to organize your code clearly by controlling access to data.
Syntax
PHP
<?php
class ClassName {
    public $property1;    // visible everywhere
    protected $property2; // visible in this class and subclasses
    private $property3;   // visible only inside this class
}
?>

public means anyone can access the property.

protected means only this class and classes that extend it can access the property.

private means only this class can access the property.

Examples
This class has three properties with different visibility levels.
PHP
<?php
class Car {
    public $color;
    protected $engineNumber;
    private $ownerName;
}
You can set public properties from outside the class, but not protected or private ones.
PHP
<?php
$car = new Car();
$car->color = 'red'; // works because color is public
// $car->engineNumber = '123'; // error: protected
// $car->ownerName = 'Alice'; // error: private
?>
A subclass can access protected properties of its parent.
PHP
<?php
class Bike extends Car {
    public function showEngine() {
        return $this->engineNumber; // allowed because protected
    }
}
Sample Program

This program shows how public, protected, and private properties behave. We access protected and private properties using public methods.

PHP
<?php
class Person {
    public $name;
    protected $age;
    private $salary;

    public function __construct($name, $age, $salary) {
        $this->name = $name;
        $this->age = $age;
        $this->salary = $salary;
    }

    public function getAge() {
        return $this->age;
    }

    public function getSalary() {
        return $this->salary;
    }
}

$person = new Person('John', 30, 50000);
echo $person->name . "\n";        // public, accessible
// echo $person->age;              // error: protected
// echo $person->salary;           // error: private

echo $person->getAge() . "\n";    // access protected via method

echo $person->getSalary() . "\n"; // access private via method
?>
OutputSuccess
Important Notes

Use public for properties you want everyone to access.

Use protected to hide properties but allow child classes to use them.

Use private to keep properties hidden inside the class only.

Summary

Properties hold data inside objects.

Visibility controls who can see or change properties: public, protected, private.

Use methods to access protected or private properties safely.