A method is a function that belongs to a class. It describes something an object can do.
<?php
class Rectangle
{
public function __construct(
public float $width,
public float $height,
) {}
public function area(): float
{
return $this->width * $this->height;
}
public function isSquare(): bool
{
return $this->width === $this->height;
}
}
$r = new Rectangle(4, 5);
echo $r->area() . "\n";
var_dump($r->isSquare());
20
bool(false)
Methods are written like functions, without the function word being different: public function area(): float. They can have parameters, return types and default values, exactly as in the functions chapter.
Methods use the object’s data
Inside a method, $this is the current object. $this->width reads that object’s own width. See $this.
Methods that change the object
<?php
class Counter
{
private int $count = 0;
public function increment(): void
{
$this->count++;
}
public function value(): int
{
return $this->count;
}
}
$c = new Counter();
$c->increment();
$c->increment();
echo $c->value();
2
Method chaining
If a method returns $this, you can call another method on the result, in one line. This is called a fluent interface.
<?php
class Query
{
private array $parts = [];
public function select(string $columns): static
{
$this->parts[] = "SELECT $columns";
return $this;
}
public function from(string $table): static
{
$this->parts[] = "FROM $table";
return $this;
}
public function build(): string
{
return implode(" ", $this->parts);
}
}
echo (new Query())->select("name, price")->from("products")->build();
SELECT name, price FROM products
Method names
Use camelCase and start with a verb: getTotal(), addItem(), isPaid(), hasStock(). Methods that return a boolean usually start with is, has or can.
Keep methods small
A method should do one thing and fit on one screen. If a method has an “and” in its description (“it validates and saves and sends an email”), split it.
Calling a method that does not exist
<?php
class Dog {}
try {
(new Dog())->fly();
} catch (Error $e) {
echo $e->getMessage();
}
Call to undefined method Dog::fly()
Methods can call each other
<?php
class Cart
{
private array $prices = [100, 250];
public function subtotal(): float
{
return array_sum($this->prices);
}
public function total(): float
{
return $this->subtotal() * 1.18;
}
}
echo (new Cart())->total();
413
Exercise: a bank account
Create a class Account with a private balance. Add deposit(float $amount), withdraw(float $amount) (do not allow going below 0) and balance(): float.
Show a possible solution
<?php
class Account
{
private float $balance = 0;
public function deposit(float $amount): void
{
$this->balance += $amount;
}
public function withdraw(float $amount): bool
{
if ($amount > $this->balance) {
return false;
}
$this->balance -= $amount;
return true;
}
public function balance(): float
{
return $this->balance;
}
}
$account = new Account();
$account->deposit(500);
var_dump($account->withdraw(800));
$account->withdraw(200);
echo $account->balance();
bool(false)
300