Methods in PHP

PHP supports methods defined on classes, which are similar to structs in other languages.

<?php

class Rectangle {
    public $width;
    public $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    // This `area` method is defined on the Rectangle class.
    public function area() {
        return $this->width * $this->height;
    }

    // Methods can be defined for either the class itself or instances.
    // Here's an example of an instance method.
    public function perimeter() {
        return 2 * $this->width + 2 * $this->height;
    }
}

function main() {
    $r = new Rectangle(10, 5);

    // Here we call the 2 methods defined for our class.
    echo "area: " . $r->area() . "\n";
    echo "perimeter: " . $r->perimeter() . "\n";

    // PHP automatically handles method calls on objects.
    // There's no need for explicit pointer dereferencing.
    $rp = $r;
    echo "area: " . $rp->area() . "\n";
    echo "perimeter: " . $rp->perimeter() . "\n";
}

main();

To run the program, save it as methods.php and use the PHP interpreter:

$ php methods.php
area: 50
perimeter: 30
area: 50
perimeter: 30

In PHP, classes are used to define objects with properties and methods. The Rectangle class is defined with width and height properties, and area() and perimeter() methods.

Methods in PHP are always defined on the class itself, and there’s no distinction between value and pointer receivers as in some other languages. PHP uses reference counting and copy-on-write, so passing objects to methods is efficient by default.

The main() function demonstrates creating an instance of the Rectangle class and calling its methods. In PHP, the -> operator is used to access object properties and methods.

Unlike some languages, PHP doesn’t require explicit pointer dereferencing. When you assign an object to a new variable ($rp = $r), both variables refer to the same object. Changes made through either variable will affect the same underlying object.

Next, we’ll look at PHP’s mechanism for defining abstract types and polymorphism: interfaces.