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
PHP OOP Introduction
PHP Class
PHP Objects
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?