Home / Kode / Understanding the Arrow Operator (->) in PHP

Understanding the Arrow Operator (->) in PHP

What Does -> Do in PHP?

The -> operator in PHP accesses properties and methods of an object. It dereferences an object instance to interact with its members.

class Car {
    public $color = 'red';
    public function drive() {
        echo 'Driving';
    }
}

$myCar = new Car();
echo $myCar->color;  // Outputs: red
$myCar->drive();     // Outputs: Driving

Use -> for objects, not arrays (use [] or => for arrays).

Origins of the -> Operator in PHP

PHP borrows -> from C and C++. In C, -> accesses struct or class members via pointers:

struct Point {
    int x;
};
struct Point *p = malloc(sizeof(struct Point));
p->x = 10;  // Same as (*p).x

PHP’s creator, Rasmus Lerdorf, modeled early object syntax after C. PHP adopted -> for consistency with pointer-like behavior in OOP.

PHP -> vs JavaScript Dot (.)

JavaScript uses dot notation (.) for object properties:

const car = { color: 'red' };
console.log(car.color);  // red

PHP uses -> to distinguish objects from associative arrays (which use => or []). This avoids ambiguity in a loosely typed language.

FeaturePHPJavaScript
Operator->.
Arrays[] or =>. or []
OriginC/C++C/Prototypal

Common Use Cases and Tips

  • Instantiation: Always use new before ->.
  • Chaining: $obj->method()->another();
  • Static Access: Use :: instead (ClassName::method()).
  • Null-safe (PHP 8+): ?-> prevents errors on null.

Avoid confusing -> with :: (scope resolution).

Why PHP Chose -> Over Dot

Dot (.) in PHP means string concatenation. Using it for objects would conflict. -> clearly signals object orientation, aligning with PHP’s C-inspired roots.

Répondre

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *