Object Operator in PHP

Sheeraz Gul Feb 23, 2022
  1. Use Object Operator to Access the Members of an Object in PHP
  2. Use Object Operator to Access the Properties of a Class in PHP
Object Operator in PHP

The object operator (->) is used in object-oriented programming in PHP. It is used to instantiate a class or can be used to access any object in PHP.

This tutorial will demonstrate how to use the object operator in PHP.

Use Object Operator to Access the Members of an Object in PHP

In the following example, we create a class then instantiate it to access the members of the provided object using the object operator (->).

Example:

<?php
$demo_obj = (object) array('1' => 'John','2' => 'Shawn','3' => 'Michelle');
echo $demo_obj->{'1'}."<br>";
echo $demo_obj->{'2'}."<br>";
echo $demo_obj->{'3'};
?>

Output:

John
Shawn
Michelle

Use Object Operator to Access the Properties of a Class in PHP

The object operator (->) is also used to access the properties of a class. The code below creates a class with two variables and one method.

Example:

<?php
class Demo_Class {
	public $demo;
    public $demo1 = "This is delftstack";

    public function Demo_Method() {
    echo "This is delftstack from demo method.";
    }
}
$demoinstance = new Demo_Class();

$demoinstance->demo="delftstack"; // Assign "delftstack" to "demo" variable
echo $demoinstance->demo;
echo "<br>";
echo $demoinstance->demo1; //print demo 1
echo "<br>";
$demoinstance->Demo_Method(); // Run "Demo_Method()"
?>

Output:

delftstack
This is delftstack
This is delftstack from demo method.

The object operator (->) can also be used to assign values to variables and call methods.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - PHP Object