PHP OOP - Access Modifiers

PHP - Access Modifiers


Access modifiers in PHP control the visibility of class properties and methods.


PHP provides three types of access modifiers:


  • public - Accessible from anywhere (inside or outside the class). This is default
  • protected - Accessible within the class and inherited (child) classes only
  • private - Accessible only inside the class that defines it


In the following example we have added three different access modifiers to three properties (brand, engine, and price). Here, if you try to access the brand property it will work fine (because the brand property is public, and can be accessed from everywhere). However, if you try to access the engine or color property it will result in a fatal error (because the engine and color property are protected and private):

Example
<?php
class Car {
public $brand = "Toyota"; // Can be accessed from anywhere
protected $engine = "V8"; // Can be accessed within class and subclasses
private $price = "$30,000"; // Can only be accessed within this class
public function showDetails() {
return "Brand: $this->brand, Engine: $this->engine, Price: $this->price";
}
}
$myCar = new Car();
echo $myCar->brand; // Allowed (public)
// echo $myCar->engine; // Error (protected)
// echo $myCar->price; // Error (private)
echo "<br>" . $myCar->showDetails(); // Allowed (public method)
?>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.