Classes and objects
So far data and functions have lived separately. An object brings them together: it holds data and knows how to work with it. This approach is called object-oriented programming, or OOP.
Class and object
A class is a blueprint, and an object is a thing built from it. The class describes what data an object has; the object itself is created with the new operator:
<?php
class User
{
public string $name = 'Guest';
}
$user = new User();
$user->name = 'Anna';
echo $user->name; // AnnaVariables inside a class are called properties. You access a property through the arrow ->, and the property name is written without the $ sign.
Methods
A function inside a class is called a method. Inside a method the current object is available as $this:
<?php
class User
{
public string $name = 'Guest';
public function greet(): string
{
return "Hello, {$this->name}!";
}
}
$user = new User();
$user->name = 'Anna';
echo $user->greet(); // Hello, Anna!A method works with the data of exactly the object it was called on.
Objects are independent
You can create any number of objects from one class, and each has its own property values:
<?php
class User
{
public string $name = 'Guest';
}
$first = new User();
$second = new User();
$first->name = 'Anna';
echo $first->name, "\n"; // Anna
echo $second->name; // GuestAssignment does not copy an object
A variable holds a reference to the object, not the object itself. After an assignment both variables point to the same object:
<?php
class User
{
public string $name = 'Guest';
}
$a = new User();
$b = $a;
$b->name = 'Oleg';
echo $a->name; // OlegTo get an independent copy, use the clone operator: $b = clone $a;.
A common mistake
Inside a method it is easy to write $name instead of $this->name. They are different things: $name is an ordinary local variable that does not exist, and PHP prints an Undefined variable warning.