Menu
Coddy logo textTech

Methods

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 5 of 91.

Methods are functions that belong to a class. They define the behaviors or actions that objects can perform.

Here is an example of a class with methods:

<?php
class Calculator {
    public function greet() {
        echo "Hello! I'm a calculator.\n";
    }

    public function add($a, $b) {
        return $a + $b;
    }

    public function multiply($x, $y) {
        $result = $x * $y;
        echo $x . " × " . $y . " = " . $result . "\n";
        return $result;
    }
}

Create a calculator object:

$myCalc = new Calculator();

Call a method that doesn't need parameters:

$myCalc->greet();

Call methods with parameters:

$sumResult = $myCalc->add(5, 3);
echo $sumResult . "\n";

Call a method that both prints and returns a value:

$product = $myCalc->multiply(4, 7);

Output:

Hello! I'm a calculator.
8
4 × 7 = 28

Methods can:

  • Take parameters like add($a, $b)
  • Return values like return $a + $b;
  • Print output directly like echo "Hello!";
  • Do both printing and returning

Key Point: Methods define what your objects can do. Use the public function keywords to define a method inside a class. Call methods using the -> operator on an object.

challenge icon

Challenge

Easy

Create a BankAccount class in bank_account.php with:

  1. A public $balance property
  2. A deposit method that takes an amount and adds it to the balance
  3. A withdraw method that takes an amount and subtracts it from the balance
  4. A getBalance method that returns the current balance

Then in driver.php, create an account with balance 0, deposit $100, withdraw $30, and print the balance in the format: "Current balance: $[balance]"

Cheat sheet

Methods are functions that belong to a class and define the behaviors or actions that objects can perform.

Define methods inside a class using public function:

<?php
class Calculator {
    public function greet() {
        echo "Hello! I'm a calculator.\n";
    }

    public function add($a, $b) {
        return $a + $b;
    }

    public function multiply($x, $y) {
        $result = $x * $y;
        echo $x . " × " . $y . " = " . $result . "\n";
        return $result;
    }
}

Call methods using the -> operator on an object:

$myCalc = new Calculator();
$myCalc->greet();
$sumResult = $myCalc->add(5, 3);
$product = $myCalc->multiply(4, 7);

Methods can:

  • Take parameters: add($a, $b)
  • Return values: return $a + $b;
  • Print output: echo "Hello!";
  • Do both printing and returning

Try it yourself

<?php
require_once 'bank_account.php';

$myAccount = new BankAccount();
$myAccount->balance = 0;

// TODO: Deposit 100

// TODO: Withdraw 30

// TODO: Print the balance in format: "Current balance: $[balance]"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming