PHP Objects

An object is a real thing created from a class. A class alone does nothing, you need to create an object of the class to use it. You create an object with the new keyword.

$objClass = new MyClass();

If you have not read it yet, first learn how to write a PHP class.


Create objects and use them

Use the arrow operator (->) to set a property or to call a method of an object.

<?php
class Car {
    public $brand;
    public $color = "White";

    public function start() {
        return $this->brand . " is started";
    }
}

$car1 = new Car();
$car1->brand = "Swift";

$car2 = new Car();
$car2->brand = "Creta";
$car2->color = "Black";

echo $car1->start() . "<br>";
echo $car2->start() . "<br>";
echo $car1->color . " " . $car2->color;
?>

Output:

Tutorials Class - Output Window

Swift is started
Creta is started
White Black

Each object has its own copy of the properties. Changing the color of $car2 does not change $car1.


Compare objects: == and ===

  • == is true when both objects are of the same class and have the same property values.
  • === is true only when both variables point to the same object.
<?php
class Car {
    public $brand;
    public $color = "White";
}

$a = new Car();
$b = new Car();
$c = $a;

var_dump($a == $b);
var_dump($a === $b);
var_dump($a === $c);
?>

Output:

Tutorials Class - Output Window

bool(true)
bool(false)
bool(true)


Check the class of an object

The instanceof operator tells if an object is made from a class (or its child class).

<?php
class Car {}

$a = new Car();

var_dump($a instanceof Car);
?>

Output:

Tutorials Class - Output Window

bool(true)


Copy and clone an object

When you assign an object to another variable, PHP does not copy it. Both variables point to the same object. To make a real copy use the clone keyword.

<?php
class Car {
    public $brand;
}

$x = new Car();
$x->brand = "Swift";

$y = $x;          // same object
$z = clone $x;    // a new copy

$y->brand = "Creta";

echo $x->brand . " " . $z->brand;
?>

Output:

Tutorials Class - Output Window

Creta Swift

Changing $y also changed $x, because they are the same object. The clone $z kept the old value.


Summary

  • Create an object with new ClassName().
  • Use -> to access properties and methods.
  • Every object has its own property values.
  • Use === to check if two variables are the same object, and clone to copy an object.

Practice with this interview question.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?