0% found this document useful (0 votes)
9 views60 pages

IWD4340704

The document contains multiple PHP scripts for various practical exercises. These include creating a simple calculator, identifying car companies based on names, generating Fibonacci sequences, displaying multiplication tables, analyzing string lengths and word counts, sorting arrays, performing matrix operations, encoding messages in Morse code, and utilizing string functions. Each script is accompanied by HTML forms for user input and displays results accordingly.

Uploaded by

vrajc2810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views60 pages

IWD4340704

The document contains multiple PHP scripts for various practical exercises. These include creating a simple calculator, identifying car companies based on names, generating Fibonacci sequences, displaying multiplication tables, analyzing string lengths and word counts, sorting arrays, performing matrix operations, encoding messages in Morse code, and utilizing string functions. Each script is accompanied by HTML forms for user input and displays results accordingly.

Uploaded by

vrajc2810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

IWD4340704

Practical :- 2(A)

Aim :- write a script to implement a simple calculator for


mathematical operations

CODE:-
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];

switch ($operation) {
case 'add':
$result = $num1 + $num2;
break;
case 'subtract':
$result = $num1 - $num2;
break;
case 'multiply':
$result = $num1 * $num2;
break;
case 'divide':
if ($num2 != 0) {
$result = $num1 / $num2;
} else {
$result = "Cannot divide by zero";
}
break;
default:
$result = "Invalid operation";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<h1>Simple Calculator</h1>
<form method="post" action="">
<input type="number" name="num1" required placeholder="Enter first
number">
<input type="number" name="num2" required placeholder="Enter second
number">
<select name="operation" required>
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="submit" value="Calculate">
</form>

<?php
if (isset($result)) {
echo "<h2>Result: $result</h2>";
}
?>
OUTPUT-:
IWD4340704
Practical :- 3(A)

Aim: - Write a script that reads the name of the car and
displays the name of the
company the car belongs to
as per the below table:
car company
Safari,nexon,tiago,tigor Tata
XUV700,XUV300,Bolero Mahindra
I20,verna,venue,creta Hyundai
Swift,alto,baleno,brezza Suzuki

CODE: -
<?php
// Define an associative array where car names are keys and companies are values
$carCompanies = [
'Safari' => 'Tata', 'nexon' => 'Tata', 'tiago' => 'Tata', 'tigor' => 'Tata',
'XUV700' => 'Mahindra', 'XUV300' => 'Mahindra', 'Bolero' => 'Mahindra',
'I20' => 'Hyundai', 'verna' => 'Hyundai', 'venue' => 'Hyundai', 'creta' =>
'Hyundai',
'Swift' => 'Suzuki', 'alto' => 'Suzuki', 'baleno' => 'Suzuki', 'brezza' => 'Suzuki'
];

// Initialize the response message


$response = "";
// Check if the form is submitted and if the car name is provided
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['carName'])) {
$carName = trim($_POST['carName']);

// Convert car name to lowercase to handle case-insensitive matching


$carName = strtolower($carName);

// Check if the car name exists in the array and display the company name
if (array_key_exists($carName, $carCompanies)) {
$response = "The company of the car '{$carName}' is: " .
$carCompanies[$carName];
} else {
$response = "Car not found in the database.";
}
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Car Company Finder</title>
</head>
<body>
<h1>Find the Company of a Car</h1>

<!-- HTML Form to input the car name -->


<form method="POST" action="">
<label for="carName">Enter the name of the car:</label><br>
<input type="text" id="carName" name="carName" required><br><br>
<button type="submit">Find Company</button>
</form>

<h2>Result:</h2>
<p><?php echo $response; ?></p>
</body>
</html>
OUTPUT-:
IWD4340704
Practical :- 3(B)

Aim: - Write a script to display Fibonacci numbers up to a


given term.
CODE- :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$terms = $_POST['terms'];
$fibonacci = [0, 1];

for ($i = 2; $i < $terms; $i++) {


$fibonacci[$i] = $fibonacci[$i - 1] + $fibonacci[$i - 2];
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Fibonacci Sequence</title>
</head>
<body>
<h1>Fibonacci Sequence Generator</h1>
<form method="post" action="">
<input type="number" name="terms" required placeholder="Enter number
of terms">
<input type="submit" value="Generate">
</form>

<?php
if (isset($fibonacci)) {
echo "<h2>Fibonacci Sequence:</h2>";
echo implode(", ", array_slice($fibonacci, 0, $terms));
}
?>
</body>
</html>
OUTPUT- :
IWD4340704
Practical :- 3(C)

Aim: - Write a script to display a multiplication table for


the given number.

CODE-:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = $_POST['number'];
$table = [];

for ($i = 1; $i <= 10; $i++) {


$table[] = "$number x $i = " . ($number * $i);
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
</head>
<body>
<h1>Multiplication Table Generator</h1>
<form method="post" action="">
<input type="number" name="number" required
placeholder="Enter a number">
<input type="submit" value="Generate Table">
</form>

<?php
if (isset($table)) {
echo "<h2>Multiplication Table for $number:</h2>";
echo "<ul>";
foreach ($table as $line) {
echo "<li>$line</li>";
}
echo "</ul>";
}
?>
</body>
</html>
OUTPUT-:
IWD4340704
Practical :- 4(A)

Aim: - Write a script to calculate the length of a string and


count the number of words in the given string without
using string functions.

CODE-:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$inputString = $_POST['inputString'];
$length = 0;
$wordCount = 0;
$inWord = false;

// Calculate length and count words


for ($i = 0; isset($inputString[$i]); $i++) {
$length++;
if ($inputString[$i] != ' ') {
if (!$inWord) {
$wordCount++;
$inWord = true;
}
} else {
$inWord = false;
}
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>String Analysis</title>
</head>
<body>
<h1>String Length and Word Count</h1>
<form method="post" action="">
<textarea name="inputString" required placeholder="Enter
a string"></textarea>
<input type="submit" value="Analyze">
</form>

<?php
if (isset($length) && isset($wordCount)) {
echo "<h2>Results:</h2>";
echo "Length of the string: $length<br>";
echo "Number of words: $wordCount";
}
?>
</body>
</html>
OUTPUT-:

Write a script to sort a given indexed array.


IWD4340704
Practical :- 4(B)

Aim: - Write a script to sort a given indexed array.

CODE-:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$inputArray = explode(',', $_POST['inputArray']);
$length = count($inputArray);

// Simple bubble sort algorithm


for ($i = 0; $i < $length - 1; $i++) {
for ($j = 0; $j < $length - $i - 1; $j++) {
if ($inputArray[$j] > $inputArray[$j + 1]) {
// Swap
$temp = $inputArray[$j];
$inputArray[$j] = $inputArray[$j + 1];
$inputArray[$j + 1] = $temp;
}
}
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Array Sorter</title>
</head>
<body>
<h1>Sort an Indexed Array</h1>
<form method="post" action="">
<input type="text" name="inputArray" required
placeholder="Enter numbers separated by commas">
<input type="submit" value="Sort">
</form>

<?php
if (isset($inputArray)) {
echo "<h2>Sorted Array:</h2>";
echo implode(", ", $inputArray);
}
?>
</body>
</html>
OUTPUT-:
IWD4340704
Practical :- 4(C)

Aim: -write a script to perform 3 X 3 matrix multiplication.


CODE-:
<?php
function printMatrix($matrix, $title) {
echo "<h3>$title</h3><pre>";
foreach ($matrix as $row) {
echo implode(" ", $row) . "\n";
}
echo "</pre>";
}
?>

<!DOCTYPE html>
<html>
<head>
<title>3x3 Matrix Addition and Multiplication</title>
</head>
<body>
<h2>3x3 Matrix Operations</h2>

<form method="post">
<h3>Matrix A</h3>
<?php
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$name = "a{$i}{$j}";
$value = $_POST[$name] ?? '';
echo "<input type='number' name='$name'
value='$value' required>";
}
echo "<br>";
}
?>

<h3>Matrix B</h3>
<?php
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$name = "b{$i}{$j}";
$value = $_POST[$name] ?? '';
echo "<input type='number' name='$name'
value='$value' required>";
}
echo "<br>";
}
?>

<br>
<input type="submit" name="submit"
value="Calculate">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Create matrices A and B
$A = $B = [];
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$A[$i][$j] = (int)$_POST["a{$i}{$j}"];
$B[$i][$j] = (int)$_POST["b{$i}{$j}"];
}
}

// Addition
$sum = [];
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$sum[$i][$j] = $A[$i][$j] + $B[$i][$j];
}
}

// Multiplication
$product = [];
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$product[$i][$j] = 0;
for ($k = 0; $k < 3; $k++) {
$product[$i][$j] += $A[$i][$k] * $B[$k][$j];
}
}
}

// Print results
printMatrix($sum, "Matrix A + B (Addition)");
printMatrix($product, "Matrix A x B (Multiplication)");
}
?>
</body>
</html>
OUTPUT-:
IWD4340704
Practical :- 4(D)

Aim: - Write a script to encode a given message into


equivalent Morse code.
CODE-:
<?php
function encodeToMorse($message) {
$morseCode = [
'A' => '.-', 'B' => '-...', 'C' => '-.-.',
'D' => '-..', 'E' => '.', 'F' => '..-.',
'G' => '--.', 'H' => '....', 'I' => '..',
'J' => '.---', 'K' => '-.-', 'L' => '.-..',
'M' => '--', 'N' => '-.', 'O' => '---',
'P' => '.--.', 'Q' => '--.-', 'R' => '.-.',
'S' => '...', 'T' => '-', 'U' => '..-',
'V' => '...-', 'W' => '.--', 'X' => '-..-',
'Y' => '-.--', 'Z' => '--..',
'0' => '-----', '1' => '.----', '2' => '..---',
'3' => '...--', '4' => '....-', '5' => '.....',
'6' => '-....', '7' => '--...', '8' => '---..',
'9' => '----.',
' ' => '/', '.' => '.-.-.-', ',' => '--..--',
'?' => '..--..', '!' => '-.-.--'
];

$message = strtoupper($message);
$encoded = "";

for ($i = 0; $i < strlen($message); $i++) {


$char = $message[$i];
if (isset($morseCode[$char])) {
$encoded .= $morseCode[$char] . " ";
} else {
$encoded .= "? "; // Unknown character
}
}

return trim($encoded);
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Morse Code Encoder</title>
</head>
<body>
<h2>Morse Code Encoder</h2>
<form method="post">
<label>Enter your message:</label><br>
<input type="text" name="message" required
style="width: 300px;"><br><br>
<input type="submit" value="Encode">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST["message"];
$output = encodeToMorse($input);
echo "<h3>Encoded Morse Code:</h3>";
echo "<p><strong>" . htmlspecialchars($output) .
"</strong></p>";
}
?>
</body>
</html>
OUTPUT-:
IWD4340704
Practical :- 5(A)

Aim: - Write scripts using string functions:


a)to check if the given string is lowercase or not.
b)to reverse the given string.
c)to remove white spaces from the given string.
d)to replace the given word from the given string.
CODE-:
<?php
function isLowercase($str) {
return $str === strtolower($str);
}

function reverseString($str) {
return strrev($str);
}

function removeWhitespaces($str) {
return str_replace(' ', '', $str);
}

function replaceWord($str, $search, $replace) {


return str_replace($search, $replace, $str);
}
?>

<!DOCTYPE html>
<html>
<head>
<title>String Function Utilities</title>
</head>
<body>
<h2>PHP String Operations</h2>

<form method="post">
<label>Enter a string:</label><br>
<input type="text" name="inputString" required
style="width: 300px;"><br><br>

<label>Word to replace (optional):</label><br>


<input type="text" name="search"><br><br>

<label>Replace with (optional):</label><br>


<input type="text" name="replace"><br><br>

<input type="submit" value="Process">


</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST["inputString"];
$search = $_POST["search"] ?? '';
$replace = $_POST["replace"] ?? '';

echo "<h3>Results:</h3>";

// a) Check if lowercase
echo "<p><strong>a) Is lowercase?</strong> " .
(isLowercase($input) ? "Yes" : "No") . "</p>";

// b) Reverse string
echo "<p><strong>b) Reversed string:</strong> " .
reverseString($input) . "</p>";

// c) Remove white spaces


echo "<p><strong>c) Without white
spaces:</strong> " . removeWhitespaces($input) . "</p>";

// d) Replace word
if (!empty($search) && isset($replace)) {
echo "<p><strong>d) After replacing '{$search}'
with '{$replace}':</strong> " . replaceWord($input,
$search, $replace) . "</p>";
} else {
echo "<p><strong>d)</strong> No replacement
done (empty input).</p>";
}
}
?>
</body>
</html>
OUTPUT-:
IWD4340704
Practical :- 5(B)

Aim: - Write scripts using math functions:


a) to generate a random number between the given
range.
B) to display the binary, octal and hexadecimal of a
given decimal number.
C) to display the sin, cos and tan of the given angle.
CODE-:
<?php
// a) Function to generate a random number between a given
range
function generateRandomNumber($min, $max) {
return rand($min, $max);
}

// b) Function to display the binary, octal, and hexadecimal of a


given decimal number
function displayNumberSystems($decimal) {
$binary = decbin($decimal); // Convert decimal to binary
$octal = decoct($decimal); // Convert decimal to octal
$hexadecimal = dechex($decimal); // Convert decimal to
hexadecimal

return [$binary, $octal, $hexadecimal];


}
// c) Function to display the sin, cos, and tan of a given angle
function trigFunctions($angle) {
$radians = deg2rad($angle); // Convert degrees to radians
$sin = sin($radians); // Sin of the angle
$cos = cos($radians); // Cos of the angle
$tan = tan($radians); // Tan of the angle

return [$sin, $cos, $tan];


}
?>

<!DOCTYPE html>
<html>
<head>
<title>PHP Math Functions</title>
</head>
<body>
<h2>PHP Math Functions</h2>

<form method="post">
<!-- Random number range -->
<label>Enter the range for random number (min and
max):</label><br>
<input type="number" name="min" required
placeholder="Min Value">
<input type="number" name="max" required
placeholder="Max Value"><br><br>

<!-- Decimal number for binary, octal, hexadecimal


conversion -->
<label>Enter a decimal number:</label><br>
<input type="number" name="decimal"
required><br><br>

<!-- Angle in degrees for trigonometric functions -->


<label>Enter angle in degrees:</label><br>
<input type="number" name="angle" required><br><br>

<input type="submit" value="Calculate">


</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// a) Random number between given range
$min = $_POST["min"];
$max = $_POST["max"];
$randomNumber = generateRandomNumber($min, $max);
echo "<p><strong>a) Random number between $min and
$max: </strong>$randomNumber</p>";

// b) Decimal to binary, octal, hexadecimal


$decimal = $_POST["decimal"];
list($binary, $octal, $hexadecimal) =
displayNumberSystems($decimal);
echo "<p><strong>b) Conversions for
$decimal:</strong></p>";
echo "<ul>";
echo "<li>Binary: $binary</li>";
echo "<li>Octal: $octal</li>";
echo "<li>Hexadecimal: $hexadecimal</li>";
echo "</ul>";

// c) Trigonometric functions
$angle = $_POST["angle"];
list($sinValue, $cosValue, $tanValue) =
trigFunctions($angle);
echo "<p><strong>c) Trigonometric values for angle
$angle°:</strong></p>";
echo "<ul>";
echo "<li>Sin: $sinValue</li>";
echo "<li>Cos: $cosValue</li>";
echo "<li>Tan: $tanValue</li>";
echo "</ul>";
}
?>
</body>
</html>
OUTPUT-:
IWD4340704
Practical :- 6(A)

Aim: - Write a script to:


i) Define a class with constructor and destructor.
ii) Create an object of a class and access its public
properties and methods.
CODE-:
<?php
// i) Define a class with constructor and destructor
class Person {
// Public properties
public $name;
public $age;

// Constructor to initialize the object with values


public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
echo "Object created for {$this->name}.<br>";
}

// Public method
public function greet() {
echo "Hello, my name is {$this->name} and I am {$this-
>age} years old.<br>";
}

// Destructor to clean up when the object is destroyed


public function __destruct() {
echo "Object for {$this->name} is destroyed.<br>";
}
}

// ii) Create an object of the class and access its public properties
and methods
// Creating an object of the 'Person' class
$person1 = new Person("John", 25);

// Accessing public properties


echo "Name: " . $person1->name . "<br>";
echo "Age: " . $person1->age . "<br>";

// Calling a public method


$person1->greet();

// Destroying the object (this will call the destructor automatically)


unset($person1);
?>
OUTPUT-:
IWD4340704

Practical :- 6(B)

Aim: - Write a script that uses the set attribute and get
attribute methods to access a class’s private attributes
of a class.
CODE-:
<?php
// Class definition with private attributes
class Person {
// Private attributes
private $name;
private $age;

// Setter method to set the value of name


public function setName($name) {
$this->name = $name;
}

// Getter method to get the value of name


public function getName() {
return $this->name;
}
// Setter method to set the value of age
public function setAge($age) {
$this->age = $age;
}

// Getter method to get the value of age


public function getAge() {
return $this->age;
}

// Method to display details


public function displayDetails() {
echo "Name: " . $this->getName() . "<br>";
echo "Age: " . $this->getAge() . "<br>";
}
}

// Create an object of the Person class


$person1 = new Person();

// Set the private attributes using setter methods


$person1->setName("John");
$person1->setAge(25);

// Access the private attributes using getter methods


echo "<h3>Person Details:</h3>";
$person1->displayDetails();
?>
OUTPUT-:
IWD4340704
Practical :- 6(C)

Aim: - Write a script to demonstrate single,multiple and


multilevel inheritance.
CODE-:
<?php
class Animal {
public $name;

public function __construct($name) {


$this->name = $name;
}

public function speak() {


return $this->name . " makes a sound.";
}
}

class Dog extends Animal {


public function speak() {
return $this->name . " barks.";
}
}

$dog = new Dog("Buddy");


echo "<h3>Single Inheritance:</h3>";
echo $dog->speak();
echo "<br>";

interface AnimalInterface {
public function speak();
}

interface MammalInterface {
public function walk();
}

class Human implements AnimalInterface, MammalInterface {


public function speak() {
return "I can speak.";
}

public function walk() {


return "I can walk.";
}
}

$human = new Human();


echo "<h3>Multiple Inheritance (Using Interfaces):</h3>";
echo $human->speak() . " ";
echo $human->walk();
echo "<br>";

class Vehicle {
public function start() {
return "Vehicle is starting.";
}
}

class Car extends Vehicle {


public function drive() {
return "Car is driving.";
}
}

class ElectricCar extends Car {


public function charge() {
return "Electric car is charging.";
}
}

$electricCar = new ElectricCar();


echo "<h3>Multilevel Inheritance:</h3>";
echo $electricCar->start() . " ";
echo $electricCar->drive() . " ";
echo $electricCar->charge();
echo "<br>";
?>
OUTPUT-:
IWD4340704
Practical :- 6(D)

Aim: - Write a script to demonstrate method overriding and


overloading based on the number of arguments.

CODE-:
<?php
// Parent Class (Base Class)
class Animal {
public function speak($sound = null) {
if ($sound === null) {
return "The animal makes a sound.";
} else {
return "The animal says: " . $sound;
}
}
}

// Child Class (Derived Class) that overrides the speak method


class Dog extends Animal {
public function speak($sound = null) {
if ($sound === null) {
return "The dog barks.";
} else {
return "The dog says: " . $sound;
}
}
}

// Overriding Example
$dog = new Dog();
echo "<h3>Method Overriding:</h3>";
echo $dog->speak() . "<br>"; // Overridden method
echo $dog->speak("Woof!") . "<br>"; // Overridden method with
argument

// Simulating Method Overloading using __call


class Calculator {
// Overloaded method (simulating multiple signatures)
public function __call($name, $arguments) {
if ($name == "add") {
// If 1 argument, return square of the argument
(simulating overloading)
if (count($arguments) == 1) {
return $arguments[0] * $arguments[0];
}
// If 2 arguments, return sum of the arguments
elseif (count($arguments) == 2) {
return $arguments[0] + $arguments[1];
}
// If more than 2 arguments, return sum of all arguments
else {
return array_sum($arguments);
}
}
}
}

// Overloading Example
$calculator = new Calculator();
echo "<h3>Method Overloading:</h3>";
echo "Square of 5: " . $calculator->add(5) . "<br>"; // Overload
with 1 argument
echo "Sum of 5 and 10: " . $calculator->add(5, 10) . "<br>"; //
Overload with 2 arguments
echo "Sum of 1, 2, 3, 4: " . $calculator->add(1, 2, 3, 4) . "<br>"; //
Overload with more than 2 arguments

?>
OUTPUT-:
IWD4340704
Practical :- 6(E)

Aim: - Write a script to demonstrate a simple interface.


CODE-:
<?php
// Defining the interface
interface Animal {
public function makeSound();
}

// Implementing the interface in a class


class Dog implements Animal {
public function makeSound() {
return "Woof!";
}
}

class Cat implements Animal {


public function makeSound() {
return "Meow!";
}
}

// Creating objects of classes that implement the interface


$dog = new Dog();
$cat = new Cat();

// Calling the methods of the objects


echo "<h3>Interface Demonstration:</h3>";
echo "Dog sound: " . $dog->makeSound() . "<br>"; // Output:
Woof!
echo "Cat sound: " . $cat->makeSound() . "<br>"; // Output:
Meow!
?>
OUTPUT-:
IWD4340704
Practical :- 6(F)

Aim: - Write a script to demonstrate a simple abstract class.


CODE-:
<?php
// Defining an abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract public function makeSound();

// Concrete method (has a body)


public function sleep() {
return "This animal is sleeping.";
}
}

// Extending the abstract class


class Dog extends Animal {
// Providing implementation for the abstract method
public function makeSound() {
return "Woof!";
}
}
class Cat extends Animal {
// Providing implementation for the abstract method
public function makeSound() {
return "Meow!";
}
}

// Creating objects of the classes


$dog = new Dog();
$cat = new Cat();

// Calling methods from the objects


echo "<h3>Abstract Class Demonstration:</h3>";
echo "Dog sound: " . $dog->makeSound() . "<br>"; // Output:
Woof!
echo "Cat sound: " . $cat->makeSound() . "<br>"; // Output:
Meow!
echo "Dog sleep: " . $dog->sleep() . "<br>"; // Output: This
animal is sleeping.
echo "Cat sleep: " . $cat->sleep() . "<br>"; // Output: This animal
is sleeping.
?>
OUTPUT-:
IWD4340704
Practical :- 6(G)

Aim: - Write a script to demonstrate cloning of objects.


CODE-:
<?php
// Class with properties
class Person {
public $name;
public $age;

// Constructor to initialize the properties


public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

// Method to display details


public function display() {
return "Name: " . $this->name . ", Age: " . $this->age;
}

// __clone method to customize cloning behavior


public function __clone() {
// Optionally, modify properties after cloning if
needed
// For example, we can make sure the name is not the
same after cloning
$this->name = $this->name . " (Cloned)";
}
}

// Creating an original object


$originalPerson = new Person("John Doe", 30);

// Cloning the original object


$clonedPerson = clone $originalPerson;

// Displaying details of the original and cloned objects


echo "<h3>Object Cloning Demo:</h3>";
echo "Original Person: " . $originalPerson->display() .
"<br>"; // Original
echo "Cloned Person: " . $clonedPerson->display() .
"<br>"; // Cloned
?>
Output-:

You might also like