0
0
PHPprogramming~5 mins

Class declaration syntax in PHP

Choose your learning style9 modes available
Introduction

A class lets you create your own type of object with properties and actions. It helps organize code by grouping related things together.

When you want to model real-world things like a Car or a Person in your program.
When you need to group data and functions that work on that data.
When you want to create multiple similar objects with different values.
When you want to keep your code organized and reusable.
When you want to use object-oriented programming features.
Syntax
PHP
class ClassName {
    // properties
    // methods
}

Class names usually start with a capital letter.

Inside the class, you define properties (variables) and methods (functions).

Examples
This defines a class named Car with a property color and a method drive.
PHP
class Car {
    public $color;
    public function drive() {
        echo "Driving";
    }
}
This class Person has two properties and a method that says hello using the name.
PHP
class Person {
    public $name;
    public $age;

    public function greet() {
        echo "Hello, my name is " . $this->name;
    }
}
Sample Program

This program creates a Dog class with a name and a bark method. It makes a Dog named Buddy and calls bark to print a message.

PHP
<?php
class Dog {
    public $name;

    public function bark() {
        echo $this->name . " says Woof!";
    }
}

$dog = new Dog();
$dog->name = "Buddy";
$dog->bark();
?>
OutputSuccess
Important Notes

Use public to make properties and methods accessible outside the class.

The $this keyword refers to the current object inside methods.

Always end statements with a semicolon inside the class.

Summary

Classes group related data and actions together.

Use class ClassName { } to declare a class.

Inside, define properties and methods to describe the object.