How to Create an Object in PHP

An object is an instance of a class. You create a class with properties and methods. Once the class is created, you can access the object’s properties and methods using the object variable.

Define a Class

Class is the programmer-defined data type, including local methods and local variables. It is the collection of objects. The object has properties and behavior.  Classes are the blueprints of objects.

One of the significant differences between the functions and classes is that a class contains data, variables, and functions that form the package called an: ‘object’.

Syntax

<?php
 
class Actor {
 
}

We enclose a class using curly braces ( { } ) … just like you do with functions.

Create an object with a class

To create an Object, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.

Example

<?php

class Actor {

}

$millie = new Actor();
print_r($millie);

In the above code, we have defined the empty class Actor and then created an object $mille.

Actor Object
(
)

Let’s add a constructor and method to the class.

<?php

class Actor {
 
 // Properties
 public $show;
 public $character;
 
//constructor
 public function __construct($show, $character) {
 $this->show = $show;
 $this->character = $character;
 }
 
//Method
 public function details() {
 echo "Millie is as badass as " . $this->character . " in " . $this->show . ".\n";
 }
}

$millie = new Actor('Stranger Things', 'Eleven');
$millie->details();

In the above code, we have used a parameterized constructor and added a method called details that prints the string in the console.

Output

Millie is a badass as Eleven in Stranger Things.

Create an object without a class

<?php
// Create an Object 
$obj = new stdClass();

// Added property to the object
$obj->name = 'Millie Bobby Brown';
$obj->country = 'USA';

print_r($obj);

Output

stdClass Object
(
 [name] => Millie Bobby Brown
 [country] => USA
)

Here are some essential points related to objects:

  1. Classes define how objects behave. Classes do not contain any data.
  2. Objects are the instances of classes that include the data.
  3. Members are variables that belong to the object.
  4. Methods are functions that belong to the object and have access to its members.
  5. Finally, the constructor is a specific method executed when an object is created.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.