PHP Classes & Objects
In this page:
Creating a Class
You define a class with the class keyword followed by a name and a body containing properties (variables) and methods (functions) that belong to it, like class Car { public $color; function drive() {} }.
Example: Creating a Class
<?php
class Car {
public $color;
function drive() {
echo "Driving!";
}
}
?>
Login to try C/C++/Java/PHP code in the editor
Instantiating Objects
You create an object from a class using the new keyword, such as $myCar = new Car();, which allocates a fresh instance with its own independent copy of the class's properties.
Example: Instantiating Objects
<?php
class Car {
public $color;
}
$myCar = new Car();
var_dump($myCar);
?>
Login to try C/C++/Java/PHP code in the editor
Accessing and Modifying Properties
Object properties are accessed with the -> (arrow) operator, so $myCar->color = red; sets that specific object's color without affecting any other Car object you might have created.
Example: Accessing and Modifying Properties
<?php
class Car {
public $color;
}
$myCar = new Car();
$myCar->color = 'red';
echo $myCar->color;
?>
Login to try C/C++/Java/PHP code in the editor
Writing Class Methods
You can create multiple independent objects from the same class, and changes to one object's properties never affect another object's properties, since each holds its own separate state in memory.
Example: Writing Class Methods
<?php
class Car {
public $color;
}
$car1 = new Car();
$car1->color = "red";
$car2 = new Car();
$car2->color = "blue";
echo $car1->color . " " . $car2->color;
?>
Login to try C/C++/Java/PHP code in the editor
Using the $this Keyword
Methods defined inside a class can read and modify that object's own properties directly by name, without needing to pass them in as parameters, since they execute in the context of that specific object.
Example: Using the $this Keyword
<?php
class Car {
public $color = "red";
function showColor() {
echo $this->color;
}
}
$car = new Car();
$car->showColor();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: