PHP PR 8,9 (22203C0007)
PHP PR 8,9 (22203C0007)
Experiment no-8
• Create student class with Roll number, class and div C. Then class
Test which include classtest1 and class test2 data in the form of
Associative array.
You will read it and Assign ir to class data members.
Third, result class will calculate percentage and average of Test
1 and Test 2
Solution:
<?php
// Student class
class Student {
public $rollNo;
public $class;
public $division;
// Test class
class Test {
public $marks = []; // Associative array
public function setMarks($test1, $test2) {
$this->marks["Test1"] = $test1;
$this->marks["Test2"] = $test2;
}
// Result class (inherits from Student and uses Test class as a property)
class Result extends Student {
private $test; // Object of Test class
Output:
Experiment no-9
• Collect User Profile Information in Class
(Name,Email,Age,Contact Number)
Store it in file
Use Serialize and Unserialize
Solution:
<?php
class User {
public $name, $email, $age,
$contact;
function __construct($name,
$email, $age, $contact) {
$this->name = $name;
$this->email = $email;
$this->age = $age;
$this->contact = $contact;
$data = serialize([
'name' => $this->name,
'email' => $this->email,
'age' => $this->age,
'contact' => $this->contact
]) . "\n";
if
(!file_put_contents("data.txt",
$data, FILE_APPEND)) {
throw new
Exception("Failed to write to
data.txt");
}
}
function readData($inputFile,
$outputFile) {
if (!file_exists($inputFile)) {
throw new
Exception("Input file not
found");
}
$lines = file($inputFile,
FILE_IGNORE_NEW_LINES |
FILE_SKIP_EMPTY_LINES);
$output = "";
try {
$user = new User("xyz",
"[email protected]", 18,
"7400320XXX");
$user->readData("data.txt",
"output.txt");
echo "Successfully processed
the data!";
} catch (Exception $e) {
echo "Error: " . $e-
>getMessage();
}
?>
Output:
• What is Serialization
Use of Serialization and why it's important with respect to PHP
Solution:
Serialization in PHP is the process of converting data, such as arrays or
objects, into a string format so it can be stored or transferred easily. It is useful
for
saving data in files, databases, or sessions and for sending data
between systems. The serialize() function converts data into a
storable string, and unserialize() restores it
Code:
<?php
// Define a Student class
class Student {
public $name;
public $rollNo;