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 = 28Methods 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
EasyCreate a BankAccount class in bank_account.php with:
- A
public $balanceproperty - A
depositmethod that takes an amount and adds it to the balance - A
withdrawmethod that takes an amount and subtracts it from the balance - A
getBalancemethod 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]"
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern