PHP PHP OOPS - Classs Object

PHP – Access Modifiers

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

There are three types of access modifiers:

public: The property or method can be accessed from anywhere (inside or outside the class).
protected: The property or method can only be accessed within the class itself or by classes that inherit from it.
private: The property or method can only be accessed within the class in which it is defined.

Example 1: Wi-Fi Access Levels

<?php
class WiFi {
  public $networkName;       // Public property
  protected $password;       // Protected property
  private $ipAddress;        // Private property

  public function setNetworkName($name) {
    $this->networkName = $name;
  }

  protected function setPassword($password) {
    $this->password = $password;
  }

  private function setIpAddress($ip) {
    $this->ipAddress = $ip;
  }
}

$publicWiFi = new WiFi();
$publicWiFi->setNetworkName("AirportWiFi"); // OK
$publicWiFi->setPassword("airport123");     // ERROR
$publicWiFi->setIpAddress("192.168.1.1");  // ERROR
?>

Example 2: Using Access Modifiers in Methods

<?php
class WiFi {
  public $networkName; // Public property

  public function setPublicWiFi($name) {
    $this->networkName = $name;
  }

  protected function setOfficeWiFi($name) {
    echo "Setting up Office Wi-Fi: $name (Protected access)";
  }

  private function setPersonalWiFi($name) {
    echo "Setting up Personal Mobile Wi-Fi: $name (Private access)";
  }

  public function setup() {
    // Public method can access protected and private methods internally
    $this->setOfficeWiFi("OfficeWiFi");
    echo "<br>";
    $this->setPersonalWiFi("PersonalWiFi");
  }
}

$wifi = new WiFi();
$wifi->setPublicWiFi("AirportWiFi"); // OK
$wifi->setup(); // OK - internally calls protected and private methods
$wifi->setOfficeWiFi("OfficeWiFi"); // ERROR
$wifi->setPersonalWiFi("PersonalWiFi"); // ERROR
?>

Explanation of Examples:

Wi-Fi Access Levels (Properties):

The networkName property is public and accessible from anywhere.
The password property is protected and cannot be accessed directly from outside the class.
The ipAddress property is private and is completely hidden from outside the class.
Access Modifiers in Methods:

The setPublicWiFi method is public and can be called directly.
The setOfficeWiFi method is protected, so it can only be accessed by the class itself or derived classes.
The setPersonalWiFi method is private and can only be accessed from within the class.
These examples illustrate how access modifiers can be used to control and restrict access to class members in PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *