PHP| encapsulation with example in 2022

PHP| encapsulation with example in 2021
PHP| encapsulation with example in 2021

PHP| encapsulation with example

Encapsulation: The process of combining many elements into a single entity is called Encapsulation. In the field of the programming language, the process of combining data member and member function into a single entity-like class is called Data encapsulation. 

It is an important feature of object-oriented programming. It is used to prevent the direct accessibility of data member and member function and this is done by using access specifier, public, private, protected, etc

Access Specifier: It is a keyword that is used to provide accessibility of data member(variable) and member function(function) of a class. It is also called an access modifier.

Types of Access Specifiers: There are five types of access specifiers.

1. Public

2. Private

3. Protected

Public: It allows the accessibility of data member and member function to the other classes. The public element of a class can be accessed anywhere in the program.

Private: It is used to hide data member and member functions from the other classes. The private element of a class can be accessed only inside its own class. 3. the private element of a class cannot be accessed out of that class.

Protected: It is the same as private but it allows the accessibility of data member and member function to the child class. protected is used in the case of inheritance.

How to use Encapsulation in PHP?

<?php

class Intro

{

  public $name;

  private $id;

  protected $marks;

  function set_data($n,$i,$m) {

    $this->name = $n;

   $this->id = $i;

  $this->marks = $m;

  }

  function get_data() {

    echo "Student Name:".$this->name."<br>";

    echo "Student Id:".$this->id."<br>";

    echo "Student Marks:".$this->marks."<br>";

  }

}

$s = new Intro();

$s->set_data("Icoderweb",17635,96.5);

$s->get_data();

echo $s->name;

echo $s->id;

echo $s->marks;

?>

*****OUTPUT*****

Student Name:Icoderweb

Student Id:17635

Student Marks:96.5

Icoderweb

( ! ) Fatal error: Cannot access private property Intro::$rollno in C:\xampp\www\\program.php


How to use Encapsulation with output in PHP?

<?php

class Intro

{

  public $name;

  private $id;

  protected $marks;

  function set_data($n,$r,$m) {

    $this->name = $n;

   $this->id = $i;

   $this->marks = $m;

  }

  function get_data()

{

    echo "Student Name:".$this->name."<br>";

    echo "Student Id:".$this->id."<br>";

    echo "Student Marks:".$this->marks."<br>";

  }

}

$s = new Intro();

$s->set_data("Icoderweb",2021,96.5);

$s->get_data();

?>

*****OUTPUT*****

Student Name:Icoderweb

Student Id:17635

Student Marks:96.5


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.