01 · THE IDEAREAD → TRY → LEARN
Why classes?
A function takes values in and gives a value back. A class lets you keep related values and the functions that use them in one unit. The values are called properties. The functions are called methods. One instance of a class is an object.
A class definition starts with the keyword class, then a name, then a pair of curly braces. Inside the braces you declare properties and methods. The class is only a blueprint. Nothing exists until you create an object from it with new.
A first class
The example below defines Greeter. It has one property, name, and two methods. The method called __construct is the constructor. PHP runs it automatically every time you write new Greeter(...), and the arguments in the parentheses are passed to it.
class Greeter
{
public string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function greet(): string
{
return "Hello, " . $this->name . "!";
}
}
$greeter = new Greeter("Ada");
echo $greeter->greet(), PHP_EOL;Hello, Ada!
Two things to notice. First, the constructor copies its parameter into the property with $this->name = $name;. The parameter disappears when the constructor ends, but the property stays on the object. Second, greet() reads that property with $this->name. Inside a method that is called on an object, $this means "the object this method was called on". You use -> to reach a property or call a method.
Each object has its own state
You can create as many objects from one class as you like. Each one keeps its own property values, so changing one does not affect the others. Constructor parameters can have defaults, just like function parameters.
class Counter
{
private int $count;
public function __construct(int $start = 0)
{
$this->count = $start;
}
public function increment(): int
{
$this->count++;
return $this->count;
}
}
$a = new Counter();
$b = new Counter(10);
echo $a->increment(), PHP_EOL;
echo $a->increment(), PHP_EOL;
echo $b->increment(), PHP_EOL;1 2 11
The count property is private, so code outside the class cannot touch it directly. Only the methods of Counter can read or change it. That is why the class offers increment(). Use public for members that outside code is meant to use, and private for internal details.
Objects are handled by identity
When you assign an object to another variable, PHP does not copy the object. Both variables point to the same instance. The same is true when you pass an object to a function. To get an independent copy you must use clone.
class Box
{
public function __construct(public string $label)
{
}
}
$first = new Box("draft");
$second = $first;
$second->label = "final";
echo $first->label, PHP_EOL;
$copy = clone $first;
$copy->label = "copy";
echo $first->label, PHP_EOL;
echo $copy->label, PHP_EOL;final final copy
Here the constructor declares public string $label right in its parameter list. That shorthand declares the property and assigns the argument to it in one step. It does the same job as the longer form in Greeter.
Common mistakes
- Writing
nameinstead of$this->nameinside a method. A bare$nameis just a local variable and is not the property. - Writing
$this->$name. The property is accessed as$this->name, with no second dollar sign. - Forgetting
new. A class name on its own does not give you an object. - Expecting
$second = $firstto copy an object. It shares the instance. - Calling an instance method as if it were static. Methods that use
$thisneed an object.
Exercise contract
Write the function describeBook(string $title, int $pages): string. Inside the file, complete the class Book:
- The constructor receives a title and a page count and stores both in properties.
- A method
summary()reads those properties and returns text in the formTitle (N pages). - When the page count is exactly
1, the word is singular:Title (1 page). describeBook()creates aBookwithnewand returns the result ofsummary().
For example, describeBook("PHP Basics", 120) returns PHP Basics (120 pages). Zero pages is plural, so it gives (0 pages). The tests check the returned string, so do not echo it.
Recap
A class groups properties and methods. new builds an object and runs the constructor, which usually stores its arguments in properties via $this->. Instance methods read that stored state through $this. Assigning an object shares it, and clone makes a separate copy.
Functions · Strings
- Store an object property in a constructor
- Read a property from an instance method