Object-oriented programming (OOP) is a programming paradigm that uses objects to represent and manipulate data.
In PHP, OOP helps to create reusable code, increase code maintainability and reduce code duplication.
If you’re a PHP developer, you should learn OOP to write better code and improve your skills.
OOP is suitable for PHP developers who want to write reusable and maintainable code.
It’s also useful for developers who want to work with PHP frameworks like Laravel, Symfony, and CodeIgniter.
class
keyword to create a class.new
keyword to create an object.public
, private
, or protected
keywords to define properties.public
, private
, or protected
keywords to define methods.extends
keyword to inherit a class.abstract
and interface
keywords to implement polymorphism.public
, private
, or protected
keywords to encapsulate properties and methods.public
, private
, or protected
keywords to control access to properties and methods.Let’s say you’re building a website for a car dealership.
You want to create a class that represents a car and its properties.
Here’s how you could do it:
class Car {
public $make;
public $model;
public $year;
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
public function getMake() {
return $this->make;
}
public function getModel() {
return $this->model;
}
public function getYear() {
return $this->year;
}
}
$car = new Car("Honda", "Civic", 2021);
echo $car->getMake(); // Output: Honda
echo $car->getModel(); // Output: Civic
echo $car->getYear(); // Output: 2021
In this example, we created a Car
class with properties for make
, model
, and year
.
We also defined methods to get the values of these properties.
Finally, we created an object of the Car
class and called its methods to get the property values.