In this tutorial i’m going to learn what are the example of encapsulation in laravel so follow this tutorial i have mentioned in very easy way.
What is encapsulation ?
Encapsulation is a core concept in object-oriented programming (OOP). It refers to the bundling of data and the methods that operate on that data into a single unit. This allows developers to control how the data is accessed and manipulated, which can improve the security, reliability, and maintainability of the code.
Example :-
<?php
namespace App\Models;
class User
{
private $name;
private $email;
private $password;
public function __construct($name, $email, $password)
{
$this->name = $name;
$this->email = $email;
$this->password = $password;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setPassword($password)
{
$this->password = $password;
}
}
In this example, the User
class encapsulates the user’s name and email address. The name and email address are private members, which means that they can only be accessed through the public getter and setter methods. This prevents the user’s name and email address from being accidentally or maliciously modified.
Encapsulation has a number of benefits, including:
- Data protection: Encapsulation helps to protect the data from being accidentally or maliciously modified.
- Code reusability: Encapsulation makes code more reusable by hiding the internal implementation details of the class.
- Testability: Encapsulation makes code more testable by isolating the data and the code that operates on that data.
- Maintainability: Encapsulation makes code more maintainable by making it easier to change the internal implementation of the class without affecting the code that uses it.
Encapsulation is a powerful concept that can be used to improve the quality of software.