0% complete

Object-Oriented PHP · Lesson 5 of 14

Methods

Define object behavior as methods that operate on the current instance.

Lesson

Methods are functions declared inside a class. $this refers to the current object instance. Methods should preserve class invariants and provide names that describe their behavior; a method that both mutates unrelated state and performs output is difficult to test. The method below changes state through one explicit operation. Further guidance Give an object one clear responsibility and protect state that must satisfy a rule. Prefer a small public contract and composition for replaceable collaborators; use inheritance only for a genuine subtype. Test behavior through public methods instead of relying on internal implementation details. Practice task: Create a fresh example for Methods. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Methods
PHP
class Cart
{
    private int $items = 0;
    public function add(): void { $this->items++; }
    public function count(): int { return $this->items; }
}
$cart = new Cart();
$cart->add();
echo $cart->count();
Expected output
1

Key points

  • Define object behavior as methods that operate on the current instance.
  • Protect object invariants behind a small public API.
  • Prefer composition unless inheritance expresses a genuine subtype.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.