PHP Practical Slip 9 Q.B

Write a PHP Script to create a class Fruit that contains data members as Name, Color and Price. Write a member function to accept and display details of Fruit.

<?php
// Define the Fruit class
class Fruit {
    // Data members
    public $name;
    public $color;
    public $price;

    // Member function to accept details
    public function setDetails($name, $color, $price) {
        $this->name = $name;
        $this->color = $color;
        $this->price = $price;
    }

    // Member function to display details
    public function displayDetails() {
        echo "Fruit Name: " . $this->name . "<br>";
        echo "Fruit Color: " . $this->color . "<br>";
        echo "Fruit Price: $" . $this->price . "<br>";
    }
}

// Example usage
$fruit1 = new Fruit();
$fruit1->setDetails("Apple", "Red", 1.5);
$fruit1->displayDetails();

echo "<br>";

$fruit2 = new Fruit();
$fruit2->setDetails("Banana", "Yellow", 0.5);
$fruit2->displayDetails();
?>
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top