Sunday, April 28, 2024

Multiply Two Numbers Using a Class in PHP

 <?php

// Multiplier.php
// Author  : Dr. Jake Rodriguez Pomperada, MAED-IT, MIT, PHD-TM
// Date    : April 26, 2024  1:54 PM  Friday
// Tools   : Microsoft Visual Studio
//           PHP 8.1.3
// Website : http://www.jakerpomperada.com
// YouTube Channel : https://www.youtube.com/jakepomperada
// Email   : jakerpomperada@gmail.com

class Multiplier {
    // Declare instance variables with default values
    private float $num1 = 0.0;
    private float $num2 = 0.0;
    private float $result = 0.0;

    // Method to set the two numbers
    public function setNumbers(float $number1, float $number2): void {
        $this->num1 = $number1;
        $this->num2 = $number2;
    }

    // Method to get the first number
    public function getNum1(): float {
        return $this->num1;
    }

    // Method to get the second number
    public function getNum2(): float {
        return $this->num2;
    }

    // Method to perform multiplication
    public function multiply(): void {
        $this->result = $this->num1 * $this->num2;
    }

    // Method to get the result
    public function getResult(): float {
        return $this->result;
    }
}

// Create an instance of the Multiplier class
$multiplier = new Multiplier();

// Set the numbers
$multiplier->setNumbers(12.40, 4.21);

// Perform the multiplication
$multiplier->multiply();

// Get the result and instance variables using public methods
$product = $multiplier->getResult();
$valOne = $multiplier->getNum1();
$valTwo = $multiplier->getNum2();

// Print the result
echo "\n\tMultiply Two Numbers Using a Class in PHP\n";
echo "\n\tFirst Value     :  $valOne\n";  // Print the value of num1
echo "\tSecond Value    :  $valTwo\n";  // Print the value of num2
echo "\tThe Result      :  $product\n";  // Print the multiplication result
echo "\n\tEnd of Program\n\n";
?>

No comments:

Post a Comment