Home >Backend Development >PHP Tutorial >How Do PHP\'s Object Operators (`->` and `::`) Work?

How Do PHP\'s Object Operators (`->` and `::`) Work?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 04:28:08902browse

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:

  • Calling Static Methods: Static methods are defined using the static keyword and do not require an object instance. We can call them using the :: operator, followed by the method name.
class Math {
    public static function add($a, $b) {
        return $a + $b;
    }
}

$result = Math::add(5, 10); // Output: 15
  • Accessing Static Variables: Static variables belong to the class itself, not to individual instances. We can access them using the :: operator.
class Counter {
    public static $count = 0;
    public function increment() {
        self::$count++;
    }
}

Counter::increment(); // Increment the static $count
echo Counter::$count; // Output: 1
  • Calling Parent's Methods: When using inheritance, we can call a method from a parent class within a child class using the :: operator.
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn