Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Access Modifiers in PHP

Access Modifiers in PHP

Great! Let’s break down Access Modifiers in PHP — they're essential for controlling the visibility of classes, properties, and methods in Object-Oriented Programming.


? What Are Access Modifiers?

Access modifiers define how and where class properties or methods can be accessed.

PHP supports three access modifiers:

ModifierAccess Level Description
publicAccessible anywhere (inside and outside the class)
protectedAccessible within the class and by inherited (child) classes
privateAccessible only within the class itself

? Examples

? public

class Car {    public $brand = "Toyota";    public function showBrand() {        echo $this->brand;    }}$car = new Car();echo $car->brand; // ? Accessible outside the class

? protected

class Vehicle {    protected $speed = 100;    protected function getSpeed() {        return $this->speed;    }}class Bike extends Vehicle {    public function displaySpeed() {        echo $this->getSpeed(); // ? Accessible in subclass    }}$bike = new Bike();$bike->displaySpeed(); // ? Works// echo $bike->speed; // ? Error: Cannot access protected property

? private

class Person {    private $name = "Alice";    private function getName() {        return $this->name;    }    public function showName() {        return $this->getName(); // ? OK within the same class    }}$person = new Person();echo $person->showName(); // ? Outputs: Alice// echo $person->name; // ? Error: Cannot access private property

? Summary

VisibilitySame ClassSubclassOutside Class
public???
protected???
private???
Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql