PHP - Methods

In PHP, methods are functions defined within a class that encapsulate behaviors associated with that class. They allow you to define the actions or operations that objects of the class can perform. Here's how to work with methods in advanced PHP:

Defining Methods:

Methods are defined within a class and can have access modifiers (public, protected, or private) to control their visibility and accessibility.

class MyClass {

    public function publicMethod() {

        // Code here

    }

    protected function protectedMethod() {

        // Code here

    }

    private function privateMethod() {

        // Code here

    }

}

In the example above, publicMethod is public, protectedMethod is protected, and privateMethod is private.

Accessing Methods:

You can access methods using the arrow operator -> from instances of the class.

$obj = new MyClass();

$obj->publicMethod();

Using Methods:

Methods can perform various actions, manipulate data, or interact with other objects or components.

class Calculator {

    public function add($a, $b) {

        return $a + $b;

    }

    public function subtract($a, $b) {

        return $a - $b;

    }

}

$calculator = new Calculator();

$result = $calculator->add(5, 3);

echo $result;  // Output: 8

Visibility and Encapsulation:

Access modifiers control the visibility of methods:

public: Accessible from anywhere.

protected: Accessible within the class and its derived classes.

private: Accessible only within the class itself.

class BankAccount {

    private $balance = 0;

    public function deposit($amount) {

        $this->balance += $amount;

    }

    public function getBalance() {

        return $this->balance;

    }

}

$account = new BankAccount();

$account->deposit(100);

echo $account->getBalance();  // Output: 100

Method Parameters and Return Values:

Methods can accept parameters and return values. Parameters allow you to pass data to methods, and return values allow methods to provide results.

class Math {

    public function add($a, $b) {

        return $a + $b;

    }

}

$math = new Math();

$result = $math->add(5, 7);

echo $result;  // Output: 12

Static Methods:

Static methods belong to the class itself rather than an instance. They can be accessed without creating an object.

class Utility {

    public static function square($number) {

        return $number * $number;

    }

}

$result = Utility::square(4);

echo $result;  // Output: 16

Methods are essential for encapsulating behavior within classes and defining the actions objects can take. By controlling access and visibility, you ensure proper data abstraction and encapsulation principles in your code.