Introduction to PHP objects
Definition
In PHP, objects are instances of a class, which is a blueprint for creating
objects with specific properties and methods.
An object is a data type that can store data and functions together in a
single unit. Objects are created using the new keyword followed by the
class name. Once an object is created, you can access its properties and
methods using the arrow notation (->).
A class can have properties, which are variables that store data, and
methods, which are functions that perform actions on the object. Classes
can also have constructors, which are special methods that are called
when an object is created, and destructors, which are special methods
that are called when the object is destroyed.
Examples
class Car {
public $make;
public $model;
public $year;
public $color;
public function startEngine() {
return "Engine started";
}
}
$myCar = new Car();
$myCar->make = "Toyota";
$myCar->model = "Camry";
$myCar->year = 2020;
$myCar->color = "black";
echo $myCar->startEngine(); // Output: Engine started
In this example, the Car class has four properties: make, model, year,
and color. It also has one method: startEngine(). A new object of the
class Car is created and assigned to the variable $myCar, after that, the
properties of the object are set, and the method of the object is called.
Object-oriented programming (OOP) is a programming paradigm that is
based on objects, classes, and their interactions. OOP allows you to create
modular and reusable code, making it easier to maintain and update.
<?php
class Person {
public $name;
public $age;
public $gender;
public function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
public function introduce() {
return "Hello, my name is " . $this->name . ", I am " . $this->age . "
years old and I am " . $this->gender . ".";
}
}
$person1 = new Person("John", 30, "male");
$person2 = new Person("Mary", 25, "female");
echo $person1->introduce(); // Output: Hello, my name is John, I am 30
years old and I am male.
echo $person2->introduce(); // Output: Hello, my name is Mary, I am 25
years old and I am female.
?>