HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP OOP - Classes and Objects

In PHP, classes and objects are fundamental concepts of object-oriented programming (OOP). Here's a basic overview:

Class:

A class is a blueprint for creating objects. It defines the properties (variables) and methods (functions) that will be associated with the objects created from that class.

Example

<!DOCTYPE html>
class Car {
    // Properties
    public $brand;
    public $model;
    
    // Methods
    public function start() {
        echo "The {$this->brand} {$this->model} is starting.";
    }
    
    public function stop() {
        echo "The {$this->brand} {$this->model} is stopping.";
    }
}

</html>
You can click on above box to edit the code and run again.

Output

Object:

An object is an instance of a class. It's a concrete entity based on the class, with its own unique set of property values.

Example

<!DOCTYPE html>
$car1 = new Car();
$car1->brand = "Toyota";
$car1->model = "Camry";

$car2 = new Car();
$car2->brand = "Ford";
$car2->model = "Mustang";

</html>
You can click on above box to edit the code and run again.

Output