PHP Methods
What Are Methods?
In simple terms: Methods are the actions an object can perform — the functions that belong to a class. A shopping cart can add() an item, remove() one, and calculate its total(). Properties hold an object's data; methods work with that data.
Technically: A method is a function declared inside a class, with a visibility (public, protected, or private). Non-static methods are called on an object with -> and can access the object through $this. Methods support everything regular functions do: typed parameters, default values, return types, variadics, and named arguments.
Methods vs Functions
| Function | Method | |
|---|---|---|
| Declared | At the top level of a file | Inside a class |
| Called with | calculateTotal($items) | $cart->total() |
| Data | Receives everything through parameters | Can also use the object's properties via $this |
| Visibility | Always global | public, protected, or private |
Defining and Calling Methods
Syntax
class ClassName
{
visibility function methodName(Type $param): ReturnType
{
// body, may use $this
}
}
Example
<?php
class Temperature
{
private float $celsius = 0.0;
public function setCelsius(float $celsius): void
{
if ($celsius < -273.15) {
throw new InvalidArgumentException('Temperature below absolute zero.');
}
$this->celsius = $celsius;
}
public function celsius(): float
{
return $this->celsius;
}
public function fahrenheit(): float
{
return $this->celsius * 9 / 5 + 32;
}
}
$chennai = new Temperature();
$chennai->setCelsius(34.5);
echo "Celsius: " . $chennai->celsius() . "\n";
echo "Fahrenheit: " . $chennai->fahrenheit() . "\n";
try {
$chennai->setCelsius(-300);
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Output
Celsius: 34.5
Fahrenheit: 94.1
Error: Temperature below absolute zero.
How It Works
setCelsius()changes the object's state, but only after validating the value.celsius()returns the stored value;fahrenheit()calculates a value from it.- Because the property is private, the only way to set the temperature is through
setCelsius(), so an invalid temperature can never be stored.
Commands and Queries
A useful guideline for designing methods is command–query separation:
| Kind | Purpose | Returns | Example |
|---|---|---|---|
| Command | Changes the object's state | Nothing (void), or $this for chaining | add(), remove(), setCelsius() |
| Query | Answers a question | A value; does not change state | total(), itemCount(), isEmpty() |
Queries without side effects can be called any number of times safely, which makes code easier to understand and test.
Naming Conventions
- Commands: verbs —
add(),applyCoupon(),cancel(),markAsPaid(). - Queries: nouns or questions —
total(),itemCount(),isEmpty(),hasDiscount(),canBeCancelled(). - Methods are named in camelCase.
Getters and Setters
Getters return property values; setters change them. A setter is only valuable if it protects the data — otherwise a public property would do the same:
<?php
class Product
{
private float $price = 0.0;
public function price(): float
{
return $this->price;
}
public function changePrice(float $newPrice): void
{
if ($newPrice <= 0) {
throw new InvalidArgumentException('Price must be positive.');
}
$this->price = round($newPrice, 2);
}
}
$lamp = new Product();
$lamp->changePrice(1299.999);
echo $lamp->price() . "\n";
Output
1300
Naming the setter after the business action (changePrice(), markAsShipped()) rather than generically (setPrice()) documents intent. Avoid writing a getter and setter for every property by default; many properties should only change through meaningful actions, and some should never change after construction (see Readonly Properties). In PHP 8.4, property hooks offer another way to add validation to property access (see Property Hooks (PHP 8.4)).
Private Helper Methods
Break long methods into smaller private methods. They are internal details of the class and cannot be called from outside:
<?php
class PasswordPolicy
{
public function check(string $password): array
{
$problems = [];
if (!$this->isLongEnough($password)) {
$problems[] = 'at least 12 characters';
}
if (!$this->hasDigit($password)) {
$problems[] = 'a digit';
}
return $problems;
}
private function isLongEnough(string $password): bool
{
return mb_strlen($password) >= 12;
}
private function hasDigit(string $password): bool
{
return preg_match('/\d/', $password) === 1;
}
}
$policy = new PasswordPolicy();
echo 'Missing: ' . implode(', ', $policy->check('secret')) . "\n";
var_dump($policy->check('correct-horse-42'));
Output
Missing: at least 12 characters, a digit
array(0) {
}
The public method check() reads like a summary of the rules, while each rule's details live in a small, well-named private method. Private methods can be changed freely without affecting code that uses the class.
Calling Methods Dynamically
<?php
class ReportExporter
{
public function toCsv(array $rows): string
{
return implode("\n", array_map(fn(array $r): string => implode(',', $r), $rows));
}
public function toJson(array $rows): string
{
return json_encode($rows);
}
}
$exporter = new ReportExporter();
$rows = [['id' => 1, 'name' => 'Asha'], ['id' => 2, 'name' => 'Bala']];
$formats = ['csv' => 'toCsv', 'json' => 'toJson'];
$method = $formats['json'];
echo $exporter->$method($rows) . "\n";
var_dump(method_exists($exporter, 'toXml'));
$toCsv = $exporter->toCsv(...);
echo $toCsv($rows) . "\n";
Output
[{"id":1,"name":"Asha"},{"id":2,"name":"Bala"}]
bool(false)
1,Asha
2,Bala
$exporter->$method(...)calls the method whose name is in$method. As with variable functions, map user input to an allow-list of method names first.method_exists()checks whether a method is declared.$exporter->toCsv(...)(PHP 8.1+) creates a closure bound to the object, which can be passed around as a callback.
Practical Example: A Shopping Cart
<?php
class ShoppingCart
{
private const COUPONS = ['SAVE10' => 10, 'FEST20' => 20];
private array $items = [];
private int $discountPercent = 0;
public function add(string $sku, string $name, float $price, int $quantity = 1): static
{
$this->assertValidQuantity($quantity);
$current = $this->items[$sku]['quantity'] ?? 0;
$this->items[$sku] = ['name' => $name, 'price' => $price, 'quantity' => $current + $quantity];
return $this;
}
public function updateQuantity(string $sku, int $quantity): static
{
if ($quantity === 0) {
unset($this->items[$sku]);
return $this;
}
$this->assertValidQuantity($quantity);
$this->items[$sku]['quantity'] = $quantity;
return $this;
}
public function applyCoupon(string $code): bool
{
$percent = self::COUPONS[strtoupper($code)] ?? null;
if ($percent === null) {
return false;
}
$this->discountPercent = $percent;
return true;
}
public function itemCount(): int
{
return array_sum(array_column($this->items, 'quantity'));
}
public function subtotal(): float
{
return array_sum(array_map(fn(array $item): float => $item['price'] * $item['quantity'], $this->items));
}
public function discount(): float
{
return round($this->subtotal() * $this->discountPercent / 100, 2);
}
public function total(): float
{
return $this->subtotal() - $this->discount();
}
private function assertValidQuantity(int $quantity): void
{
if ($quantity < 1 || $quantity > 99) {
throw new InvalidArgumentException('Quantity must be between 1 and 99.');
}
}
}
function summary(ShoppingCart $cart): string
{
return sprintf('%d items | subtotal ₹%.2f | discount ₹%.2f | total ₹%.2f',
$cart->itemCount(), $cart->subtotal(), $cart->discount(), $cart->total());
}
$cart = (new ShoppingCart())
->add('PEN-01', 'Gel Pen', 20, 3)
->add('NB-A5', 'Notebook', 60, 2)
->add('PEN-01', 'Gel Pen', 20);
var_dump($cart->applyCoupon('bogus'));
var_dump($cart->applyCoupon('save10'));
echo summary($cart) . "\n";
$cart->updateQuantity('NB-A5', 0);
echo summary($cart) . "\n";
Output
bool(false)
bool(true)
6 items | subtotal ₹200.00 | discount ₹20.00 | total ₹180.00
4 items | subtotal ₹80.00 | discount ₹8.00 | total ₹72.00
Step-by-Step Explanation
- Commands (
add(),updateQuantity()) change the cart and return$this, allowing chaining. AddingPEN-01twice increases its quantity to 4 instead of creating a duplicate line. applyCoupon()is a command that reports success with a boolean; codes are case-insensitive, and unknown codes leave the cart unchanged.- Queries (
itemCount(),subtotal(),discount(),total()) calculate values from the current state every time, so they are always consistent. - The private
assertValidQuantity()keeps validation in one place, used by two public methods. - The coupon list is a private class constant (see PHP Class Constants).
Code using the cart never manipulates $items directly — it can only use the cart's methods, so the cart can never contain invalid quantities.
Common Mistakes
Forgetting $this-> Inside Methods
Effect: Local variables are used instead of properties.
Fix: Use $this->property and $this->method().
Methods That Do Too Much
Effect: Long, hard-to-test methods mixing validation, calculation, and output.
Fix: Extract private helper methods with clear names.
Queries With Side Effects
Effect: Calling total() unexpectedly changes the cart.
Fix: Keep queries free of state changes.
Generic Getters and Setters for Everything
Effect: Classes that are just data containers without protection.
Fix: Expose meaningful actions; validate in commands.
Calling Methods Named by User Input
Effect: Attackers can call methods you did not intend to expose.
Fix: Map input to an allow-list of method names.
Best Practices
- Name commands with verbs and queries with nouns or questions.
- Validate input in methods that change state; keep queries side-effect free.
- Use private helper methods to keep public methods short and readable.
- Declare parameter and return types on every method.
- Return
static($this) from commands only where chaining improves readability.
Official reference: https://www.php.net/manual/en/language.oop5.basic.php