Home >Backend Development >PHP Tutorial >How Do PHP\'s Object Operators (`->` and `::`) Work?
` and `::`) Work? " />
Object Operators in PHP
In PHP, we utilize object operators to interact with objects and leverage their properties and methods. There are two primary object operators:
1. Object Operator (>)
This operator allows us to access instance properties and invoke methods within an object. Its syntax is as follows:
$object->property; $object->method();
For example, given the following class definition:
class Person { private $name; public function sayHello() { return "Hello, my name is " . $this->name; } }
We can create an instance of this class and use the object operator to access its properties and invoke its methods:
$person = new Person(); $person->name = "John Doe"; echo $person->sayHello(); // Output: "Hello, my name is John Doe"
2. Static Object Operator (::)
This operator is used in three scenarios:
class Math { public static function add($a, $b) { return $a + $b; } } $result = Math::add(5, 10); // Output: 15
class Counter { public static $count = 0; public function increment() { self::$count++; } } Counter::increment(); // Increment the static $count echo Counter::$count; // Output: 1
class Animal { public function move() { //... } } class Dog extends Animal { public function bark() { // Call the move() method from the parent class using :: parent::move(); } }
The above is the detailed content of How Do PHP\'s Object Operators (`->` and `::`) Work?. For more information, please follow other related articles on the PHP Chinese website!