Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Object

Classes and objects are the two primary elements of object-oriented programming.

A class serves as a blueprint for objects, while an object is an instance of that class.

When individual objects are created, they inherit all properties and behaviors from the class, but each object can have different values for those properties.

For example, consider a class named Car that can have properties like model, color, etc. We can define variables such as $model$color, and so on, to store the values of these properties.

When specific objects (like Volvo, BMW, Toyota, etc.) are instantiated, they inherit the properties and behaviors of the class, but each will have distinct values for its properties.

If you define a __construct() function, PHP will automatically invoke this function when you create an object from the class

Example

class Car {
 public $color;
 public $model;
 public function __construct($color, $model) {
    $this->color = $color;
    $this->model = $model;
 }
 public function message() {
    return "My car is a " . $this->color . " " . $this->model . "!";
 }
}
 
$myCar = new Car("red", "Volvo");
var_dump($myCar);