PHP how to make an object

Learn how to create an object in PHP with an example. Discover the power of object-oriented programming and see how easy it is to create objects with PHP.

Creating Objects in PHP

Objects in PHP can be created with the help of the new keyword. An object is an instance of a class. The class is like a template, or a blueprint for an object. You can think of a class like a cookie cutter; it defines the shape of a cookie and you can use it to make many instances, or cookies.

Let's take a look at an example of a Person class and how it can be used to create objects.

class Person {
  public $name;
  public $age;

  public function __construct($name, $age) {
    $this->name = $name;
    $this->age = $age;
  }
}

$person1 = new Person('John', 25);
$person2 = new Person('Mary', 22);

In this example, we have defined a Person class which has two properties: name and age. It also has a __construct() method which sets the values of these properties when an object is created. The $this keyword is used to reference the current object.

We have then created two objects from this class. The first object is $person1 which has a name of John and an age of 25. The second object is $person2 which has a name of Mary and an age of 22.

We can now use these objects to access their properties and methods. For example, if we wanted to access the age of $person1 we could use the following code:

echo $person1->age; // Outputs 25

In this example, we have used the -> operator to access the age property of $person1. This is how objects in PHP are used to access their properties and methods.

As you can see, it's quite simple to create objects in PHP. With the help of the new keyword and a class definition, you can easily create objects and access their properties and methods.

Answers (0)