In this tutorial, you shall learn how to create an instance or object of a class in PHP using new keyword, with the help of example programs.

PHP – Create Class Object

To create a class object in PHP, we can use new keyboard.

The expression: new keyword, followed by the class name, followed by arguments in parentheses returns a new instance of that class.

</>
Copy
new ClassName(argument1, argument2, ..., argumentN)

If the class constructor does not need any arguments, parenthesis after the class name is optional.

</>
Copy
new ClassName()
new ClassName

Example

In our previous tutorial, PHP class, we have given an example class Person. We shall continue with this class Person to demonstrate how to create class object in PHP.

Now, let us create an object $person1 of this class type Person, set its properties, and call a method on this object.

PHP Program

</>
Copy
<?php
  class Person {
    public $fullname;
    public $age;

    public function printDetails() {
      echo "Name : " . $this->fullname . "<br>Age : " . $this->age;
    }
  }
  
  //create object of type Person
  $person1 = new Person();
  
  //set properties of the object with values
  $person1->fullname = "Mike Turner";
  $person1->age = "24";

  //call method on the object
  $person1->printDetails();
?>

Output

PHP Create Class Object

Conclusion

In this PHP Tutorial, we learned how to create an object or instance of a user defined class, with examples.