How to create a class and object in PHP?

To create a class in PHP, use the class keyword followed by the class name. A class is like a blueprint, and an object is a real thing made from that blueprint using the new keyword.

Inside a class you can keep variables (called properties) and functions (called methods).

<?php
class Student {
    public $name;

    public function sayHello() {
        return "Hello, my name is " . $this->name;
    }
}

// Create an object using the new keyword
$student1 = new Student();
$student1->name = "Robin";

echo $student1->sayHello();
?>

Output:

Tutorials Class - Output Window

Hello, my name is Robin

You can create many objects from same class, and each object keeps its own values. Read more in PHP Class and PHP OOP Introduction.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.