PHP Program to create class in PHP


April 21, 2022, Learn eTutorial
1098

How to create a class in PHP?

To create a class in PHP we use the keyword class succeeding by class name. Inside the class, we create functions that will be class the methods. To create simple inheritance use the class keyword succeeding by extends keyword and parent class name. And to define an object we use the new keyword

Syntax


class "class_name"
{

    function "method_name"("parameters")
    {
        // code block
    }
}
class "second_class_name" extends "class_name"
{
    function "method_name"("parameters")
    {
        // code block
    }
}

ALGORITHM

Step 1: Accept the two numbers into the variables num1 and num2

Step 2: Create the Subtraction class object obj

Step 3: Call the function add(num1, num2) by using the object obj to add the numbers

Step 4: Call the function sub(num1, num2) by using the object obj to subtract the numbers

ALGORITHM function: add(num1, num2)

Step 1: Assign the computed value of 'num1 + num2' to the variable sum

Step 2: Print the value of the variable sum as the sum of num1 and num2

ALGORITHM function: sub(num1, num2)

Step 1: Assign the computed value of 'num1 - num2' to the variable sub

Step 2: Print the value of the variable sub as the subtraction of num1 and num2

PHP Source Code

                                          <?php
class Addition
{

    function add($num1, $num2)
    {
        $sum = $num1 + $num2;
        echo "$num1 + $num2 = $sum";
    }
}
class Subtraction extends Addition
{
    function sub($num1, $num2)
    {
        $sub =  $num1 - $num2;
        echo  "\n$num1 - $num2 = $sub";
    }
}
$num1 = readline("Enter the 1st number: ");
$num2 = readline("Enter the 2nd number: ");
$obj = new Subtraction;
$obj->add($num1, $num2);
$obj->sub($num1, $num2);
?>
                                      

OUTPUT

Enter the 1st number: 48
Enter the 2nd number: 15
48 + 15 = 63
48 - 15 = 33