PHP Classes & Objects
Object-Oriented Programming (OOP) lets you organize code into reusable, maintainable structures. Classes are blueprints, and objects are instances created from those blueprints!
What is a Class?
A class is a template that defines properties (data) and methods (functions) that objects will have.
Output
Click Run to execute your code
Defining a Class
<?php
class Car {
// Properties
public $brand;
public $color;
// Method
public function drive() {
echo "Driving!";
}
}
?>
Creating Objects
<?php
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->color = "red";
$myCar->drive();
?>
$this Keyword
<?php
class Car {
public $brand;
public function showBrand() {
echo $this->brand; // Access own property
}
}
?>
Summary
- Class: Blueprint/template
- Object: Instance of a class
- Properties: Variables in a class
- Methods: Functions in a class
- $this: Refers to current object
What's Next?
Next, learn about Constructors & Destructors - special methods for object initialization and cleanup!
Enjoying these tutorials?