Hi there, today I am going to explain about Object Oriented Programming in PHP with syntax and few examples.
The Object Oriented Programming Concepts are:
Let's create the class in the name of "Maths".
<?php
class Maths{
// Class properties and methods goes here
}
?>
2.Objects:
Object is an instance of a class.
When Class is created, we can create any number of objects in that Class.
In the below example, new keyword which is used to instantiate an object. Here $my_obj represents an object of the class Maths.
Creating an Object:
<?php
$my_obj = new Maths();
?>
Calling a member Function:
When an object is created, we can access variables and function of the class with the help of "->" operator.
<?php
$my_obj->add(10, 12);
?>
Example:
<?php
class Maths{
public function add($a,$b){
echo "Addition of two numbers:".$a+$b;
}
}
$my_obj = new Home();
$my_obj->add(10, 12);
?>
Output:
Addition of two numbers:22
Access Specifiers:
To set the access rights for the class methods and variables we use access specifiers.
Public: When we define class members as public, It can be accessed from anywhere, even from outside the class
Private: When we define class members as private, It can be accessed from within the class itself.
Protected: This is same as private, with one exception, the class members defined as protected can still be accessed from its subclass.
When to use Access Specifiers:
3.Encapsulation:
<?php
class Person {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName($name) {
return $this->name;
}
}
$robin = new Person();
$robin->setName('SleepyCoder');
$robin->getName();
?>
In this simple class above. Field $name is encapsulated (private). Users of the class is not aware how $name is stored in Person class. Right now the $name is stored in memory. We can modify internal code of Person class to store it to a flat file or event a database. Users of the class will not need to change any code, in fact they do not even know how $name is stored, because that is encapsulated and hided from them.
4.Inheritance:
class Shape {
public function name() {
echo "I am a shape";
}
}
class Circle extends Shape {
}
$circle = new Circle();
$circle->name(); // I am a shape
5.Polymorphism:
In OOP, abstraction is a concept in which a class has methods without implementation. The idea is to have a template and let the child class that inherits the parent class implement the method.
How to create an abstract method?
<?php
abstract class Sample {
//abstract method
public abstract function foo();
}
?>
The Object Oriented Programming Concepts are:
- Class
- Objects
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
- Class is a blueprint of an object.Which includes local methods and local variables
- The class can be declared using "Class" Keyword and followed by the name of the class and a set of curly braces ({}).
Let's create the class in the name of "Maths".
<?php
class Maths{
// Class properties and methods goes here
}
?>
2.Objects:
Object is an instance of a class.
When Class is created, we can create any number of objects in that Class.
In the below example, new keyword which is used to instantiate an object. Here $my_obj represents an object of the class Maths.
Creating an Object:
<?php
$my_obj = new Maths();
?>
Calling a member Function:
When an object is created, we can access variables and function of the class with the help of "->" operator.
<?php
$my_obj->add(10, 12);
?>
Example:
<?php
class Maths{
public function add($a,$b){
echo "Addition of two numbers:".$a+$b;
}
}
$my_obj = new Home();
$my_obj->add(10, 12);
?>
Output:
Addition of two numbers:22
Access Specifiers:
To set the access rights for the class methods and variables we use access specifiers.
Public: When we define class members as public, It can be accessed from anywhere, even from outside the class
Private: When we define class members as private, It can be accessed from within the class itself.
Protected: This is same as private, with one exception, the class members defined as protected can still be accessed from its subclass.
When to use Access Specifiers:
Access Specifier | classes | functions | variables |
---|---|---|---|
public | Not Applicable | Applicable | Applicable |
private | Not Applicable | Applicable | Applicable |
protected | Not Applicable | Applicable | Applicable |
3.Encapsulation:
- Which is used hide internal implementation details of an object.
- Visibility is the mechanism for encapsulation.
- For the security reason, we can make private method. Private method means it can be accessed within same class. Class can't access private method of other class.That's why encapsulation is known as data hiding is the main advantage for encapsulation
- Second advantage of encapsulation is you can make the class read only or write only by providing setter or getter method.
<?php
class Person {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName($name) {
return $this->name;
}
}
$robin = new Person();
$robin->setName('SleepyCoder');
$robin->getName();
?>
In this simple class above. Field $name is encapsulated (private). Users of the class is not aware how $name is stored in Person class. Right now the $name is stored in memory. We can modify internal code of Person class to store it to a flat file or event a database. Users of the class will not need to change any code, in fact they do not even know how $name is stored, because that is encapsulated and hided from them.
4.Inheritance:
- When the properties and the methods of the parent class are accessed by the child class, we call the concept has inheritance.
- Parent class decides what and how its properties/methods to be inherited by declared visibility.
class Shape {
public function name() {
echo "I am a shape";
}
}
class Circle extends Shape {
}
$circle = new Circle();
$circle->name(); // I am a shape
5.Polymorphism:
- Which is having a single form but many different implementation ways. The main purpose of polymorphism is;
- Simplify maintaining applications and making them more extendable.
- Basically it means PHP is able to process objects differently depending on their data type or class. This powerful feature allows you to write interchangeable objects that sharing the same interface.
In OOP, abstraction is a concept in which a class has methods without implementation. The idea is to have a template and let the child class that inherits the parent class implement the method.
How to create an abstract method?
- If a class has an abstract method then we also add the abstract keyword before the class.
- We use the keyword abstract to create abstract method .
- We can't instantiate an abstract class
<?php
abstract class Sample {
//abstract method
public abstract function foo();
}
?>
Inherit an abstract class
- When an abstract class is inherited by the child class, the abstract method of the parent class must be implemented in the child class.
- If the child class is not implementing an abstract method of the parent class then the child class must be declared abstract.
Dependency Injection
Dependency Injection (DI) is a design pattern used in programming to implement Inversion of Control (IoC). It allows a class to receive its dependencies from an external source rather than creating them itself. This makes the code more modular, easier to test, and promotes separation of concerns.
### Basic Example in PHP
Let's consider a simple example with a `Database` class and a `UserService` class that depends on it.
#### Without Dependency Injection
In this approach, the `UserService` creates its own `Database` instance:
```php
class Database {
public function connect() {
return "Connected to database.";
}
}
class UserService {
private $database;
public function __construct() {
$this->database = new Database(); // Hardcoded dependency
}
public function getUser() {
return $this->database->connect();
}
}
$userService = new UserService();
echo $userService->getUser(); // Output: Connected to database.
```
In this example, `UserService` is tightly coupled to `Database`, making it hard to test or replace the database connection.
#### With Dependency Injection
In this approach, we inject the `Database` instance into `UserService`:
```php
class Database {
public function connect() {
return "Connected to database.";
}
}
class UserService {
private $database;
// Dependency is injected through the constructor
public function __construct(Database $database) {
$this->database = $database;
}
public function getUser() {
return $this->database->connect();
}
}
// Create the database instance first
$database = new Database();
// Inject the database instance into UserService
$userService = new UserService($database);
echo $userService->getUser(); // Output: Connected to database.
```
### Benefits of Dependency Injection
1. Decoupling: Classes are not responsible for creating their dependencies.
2. Easier Testing: You can easily replace the `Database` class with a mock for unit tests.
3. Flexibility: You can change the implementation of the dependencies without modifying the dependent class.
### Conclusion
Dependency Injection improves code maintainability and testability by promoting loose coupling between classes. In PHP, this can be done through constructor injection, as shown in the example.
Beauuuuuuty...
ReplyDelete