How to Create Object in PHP: Syntax and Examples
In PHP, you create an object by defining a
class and then using the new keyword to make an instance of that class. For example, $obj = new ClassName(); creates an object of the class ClassName.Syntax
To create an object in PHP, you first define a class which acts like a blueprint. Then you use the new keyword followed by the class name and parentheses to create an object (instance) of that class.
- class ClassName { }: Defines a class named
ClassName. - new ClassName(): Creates a new object from the class.
- $obj = new ClassName();: Stores the new object in the variable
$obj.
php
<?php class Car { // Class body can have properties and methods } // Create an object of class Car $myCar = new Car();
Example
This example shows how to create a class with a property and a method, then create an object and use it.
php
<?php class Dog { public $name; public function __construct($name) { $this->name = $name; } public function bark() { return "Woof! My name is " . $this->name . "."; } } // Create a Dog object $dog = new Dog("Buddy"); // Call the bark method and print the result echo $dog->bark();
Output
Woof! My name is Buddy.
Common Pitfalls
Common mistakes when creating objects in PHP include:
- Forgetting to use the
newkeyword, which causes errors because PHP expects an object but gets a class name. - Not defining a constructor properly to initialize object properties.
- Trying to access properties or methods without using the object operator
->.
php
<?php // Wrong: missing 'new' keyword class Cat {} //$cat = Cat(); // This causes an error // Right way: $cat = new Cat(); // Wrong: accessing property without '->' class Bird { public $color = 'blue'; } $bird = new Bird(); //echo $bird.color; // Error // Right way: echo $bird->color; // Outputs: blue
Output
blue
Quick Reference
Here is a quick summary of how to create and use objects in PHP:
| Step | Description | Example |
|---|---|---|
| Define a class | Create a blueprint for objects | class Person { } |
| Create an object | Use new keyword | $obj = new Person(); |
| Add properties | Store data inside object | public $age; |
| Add methods | Define actions for object | public function greet() { } |
| Access members | Use -> operator | $obj->greet(); |
Key Takeaways
Use the
new keyword to create an object from a class in PHP.Define a class first as a blueprint before creating objects.
Access object properties and methods using the
-> operator.Always use a constructor to initialize object properties when needed.
Avoid forgetting
new or misusing property access to prevent errors.