PHP_QB
PHP_QB
PHP has a built-in clone keyword used for object cloning. By default, it creates a shallow copy, but you
can control cloning behavior using the __clone() magic method.
program:
<?php
class Person {
public $name;
public $age;
// Original object
$p1->name = "Alice";
$p1->age = 30;
$p2->name = "Bob";
$p2->age = 25;
?>
Ans.
Example:
<?php
class Person {
public $name = "Alice";
public $age = 30;
// Create object
$p = new Person();
// Introspection examples
echo "Class Name: " . get_class($p) . "\n";
echo "Methods:\n";
print_r(get_class_methods($p));
?>
Output:
Ans.
Serialization is the process of converting a PHP object or variable into a string format, so
it can be:
• Saved in a session
Functions Used:
✅ Example:
<?php
class Person {
public $name;
public $age;
}
// Create an object
$p1 = new Person();
$p1->name = "Alice";
$p1->age = 30;
// Serialize the object
$serializedData = serialize($p1);
echo "Serialized: " . $serializedData . "\n";
?>
Output:
Serialized: O:6:"Person":2:{s:4:"name";s:5:"Alice";s:3:"age";i:30;}
Unserialized: Name = Alice, Age = 30
Note:
PHP can only serialize data types it understands (objects, arrays, strings, etc.).
If your class has resources like file handles or database connections, they won’t serialize
properly.
Ans.
Overriding means redefining a parent class method in a child class with the same method
name, so the child class can provide its own specific behavior.
✅ Example:
<?php
class Animal {
public function sound() {
echo "Animals make sound\n";
}
}
// Test
$dog = new Dog();
$cat = new Cat();
?>
Ans.
But in PHP, real method overloading is not supported directly. Instead, PHP provides
magic methods to mimic this behavior:
Syntax:
Parameters:
Syntax:
✅ Example:
<?php
class MagicMethods {
// Called for undefined object methods
public function __call($name, $arguments) {
echo "Calling object method '$name' with arguments: ";
print_r($arguments);
}
?>
Output:
Calling object method 'greet' with arguments: Array ( [0] => Alice [1] => 25 )
Calling static method 'sayHello' with arguments: Array ( [0] => Bob )
💡 Use Cases:
Notes:
These magic methods only trigger when the method does not exist or is not accessible.
Ans.
🔨 Constructor in PHP:
✅ Syntax:
💥 Destructor in PHP
A destructor is a special method that is automatically called when the object is destroyed
or the script ends. It is used to clean up resources, like closing files or database
connections.
✅ Syntax:
✅ Example:
<?php
class Person {
public $name;
// Constructor
public function __construct($name) {
$this->name = $name;
echo "Constructor called. Hello, $this->name!\n";
}
// Destructor
public function __destruct() {
echo "Destructor called. Goodbye, $this->name!\n";
}
}
// Creating an object
$p = new Person("Alice");
// Do something
echo "Object is being used...\n";
?>
output:
Notes:
Ans.
🔨 What is a Constructor?
A constructor is a special method that gets automatically called when a new object is
created. It is used to initialize properties of a class.
1. Default Constructor
2. Parameterized Constructor
3. Constructor with Default Arguments (Simulated Overloading)
1. Default Constructor
A constructor that takes no parameters.
Ex:
<?php
class Car {
public function __construct() {
echo "Default constructor called.\n";
}
}
2. Parameterized Constructor
A constructor that accepts arguments to initialize the object.
Ex:
<?php
class Car {
public $brand;
public $model;
?>
Ex:
<?php
class Car {
public $brand;
public function __construct($brand = "Default Brand") {
$this->brand = $brand;
echo "Brand: $this->brand\n";
}
}
?>
?>
Ans
Code Reusability
Easier Maintenance
Logical Grouping
Ans..
1. Single Inheritance
Definition:
A child class inherits from one parent class.
🔹 Example:
<?php
class Animal {
public function eat() {
echo "Animal is eating.\n";
}
}
?>
2. Multilevel Inheritance
Definition:
A class inherits from a child class, forming a chain (grandparent → parent → child).
🔹 Example:
<?php
class Animal {
public function eat() {
echo "Animal is eating.\n";
}
}
?>
3. Hierarchical Inheritance
Definition:
Multiple classes inherit from the same parent class.
🔹 Example:
<?php
class Animal {
public function eat() {
echo "Animal is eating.\n";
}
}
?>
10. How multiple inheritance is achieved in PHP or Explain interface with example.
Ans.
How is Multiple Inheritance achieved in PHP?
🔴 Problem:
PHP does not support multiple inheritance directly through classes — meaning, a class
cannot extend more than one class.
Syntax:
interface InterfaceName {
public function method1();
}
🔹 Example:
<?php
interface Logger {
public function log($message);
}
interface Printer {
public function printData($data);
}
A Trait is a mechanism for reusing code in multiple classes in PHP. Traits help overcome
PHP’s limitation of no multiple class inheritance.
// Testing
$machine = new Machine();
$machine->log("Start machine");
$machine->printData("Document.pdf");
?>
✅ Syntax of Trait:
trait TraitName {
public function methodName() {
// method body
}
}
class MyClass {
use TraitName;
}
Example;
<?php
// First Trait
trait Logger {
public function log($msg) {
echo "Log: $msg\n";
}
}
// Second Trait
trait Printer {
public function print($data) {
echo "Print: $data\n";
}
}
// Test
$obj = new Machine();
$obj->start();
$obj->log("System boot successful");
$obj->print("Report.pdf");
?>
Important Notes:
If two traits have methods with the same name, you must resolve conflicts using insteadof
and as keywords.
Traits cannot be instantiated on their own — they are included inside classes.
11. Create a class as “Percentage” with two properties length & width. Calculate area of
rectangle for two objects.
Ans.
<?php
class Percentage {
public $length;
public $width;
?>
Chapter 4 (CO 4)
Ans..
✅ GET Method
🔹 Features:
Sends data through the URL
Can be bookmarked
🔹 Example:
// get_example.php
<?php
$name = $_GET['name'];
echo "Hello, $name!";
?>
✅ POST Method
🔹 Features:
Sends data in the request body (not in the URL)
Cannot be bookmarked
No size limitations
🔹 Example:
// post_example.php
<?php
$name = $_POST['name'];
echo "Hello, $name!";
?>
Ans.
Ans.
A session is a way to store user data on the server across multiple pages.
It must be called at the beginning of your script before any HTML output.
Example:
<?php
session_start(); // Start the session
4. Answer the following: i) start session ii) Get session variables ii) Destroy session
Ans.
i) Start a Session
Ex:
<?php
session_start(); // Start or resume a session
?>
<?php
session_start(); // Always start session before accessing it
<?php
session_start(); // Start the session first
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>
After this, the $_SESSION array is empty, and the session is terminated.
Ans.
Let's create a simple PHP form to collect Employee details and then display the submitted
values on a separate page.
Step 1: employee_form.html
<label>Address:</label>
<textarea name="address" rows="3" cols="30" required></textarea><br><br>
<label>Mobile No:</label>
<input type="tel" name="mobile_no" pattern="[0-9]{10}" required><br><br>
<label>Date of Birth:</label>
<input type="date" name="dob" required><br><br>
<label>Post:</label>
<select name="post" required>
<option value="Manager">Manager</option>
<option value="Developer">Developer</option>
<option value="Designer">Designer</option>
<option value="HR">HR</option>
</select><br><br>
<label>Salary:</label>
<input type="number" name="salary" required><br><br>
Step 2: display_employee.php
Ans.
✅ Types of Validation:
Server-side Validation (Done on the server using PHP or other backend language)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$email = $_POST['email'];
$age = $_POST['age'];
// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.<br>";
}
Ans.
✅ What is a Cookie?
A cookie is a small piece of data that a server stores on the user's browser to remember
information across different pages or visits.
Uses of Cookies:
Important Notes:
They can be seen and edited by users, so never store sensitive info in cookies.
Ans.
1. Create a Cookie
Use the setcookie() function:
<?php
// Syntax: setcookie(name, value, expire_time)
setcookie("username", "Alice", time() + 3600); // Expires in 1 hour
echo "Cookie has been set.";
?>
<?php
// Update the existing cookie
setcookie("username", "Bob", time() + 3600); // New value is Bob
echo "Cookie has been updated.";
?>
<?php
// Delete the cookie by setting its expiry in the past
setcookie("username", "", time() - 3600);
echo "Cookie has been deleted.";
?>
🔍 To Access a Cookie
Use the $_COOKIE superglobal array:
<?php
if (isset($_COOKIE['username'])) {
echo "Welcome, " . $_COOKIE['username'];
} else {
echo "No cookie found.";
}
?>
Ans.
The mail() function is used to send emails directly from a PHP script.
✅ Syntax:
<?php
$to = "[email protected]"; // Receiver
$subject = "Welcome to My Website"; // Subject
$message = "Hello! Thank you for signing up."; // Message body
$headers = "From: [email protected]"; // Header
Important Notes:
For reliable sending, especially with Gmail or external services, use libraries like
PHPMailer or SMTP authentication.
•
Chapter 5 (CO 5)
1. Write syntax of Connecting PHP Webpage with MySQL
Ans.
Here's the syntax to connect a PHP webpage with a MySQL database using mysqli:
<?php
$servername = "localhost"; // usually "localhost"
$username = "root"; // default for local server
$password = ""; // default is empty in XAMPP
$dbname = "your_database"; // name of your database
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
Ans.
<?php
// Create connection
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create table
$createTable = "CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
salary INT
)";
mysqli_query($conn, $createTable);
// Insert record
$insertData = "INSERT INTO employees (name, email, salary)
VALUES ('Alice Smith', '[email protected]', 45000)";
if (mysqli_query($conn, $insertData)) {
echo "Record inserted successfully!";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
2. Update Record
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Update salary of employee with id = 1
$update = "UPDATE employees SET salary = 50000 WHERE id = 1";
if (mysqli_query($conn, $update)) {
echo "Record updated successfully!";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
3. Delete Record
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $delete)) {
echo "Record deleted successfully!";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Ans.
mysqli_query($conn, $sql);
if (mysqli_query($conn, $sql_in)) {
echo "Data inserted successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
echo "Email: " . $row["email"] . "<br>";
echo "Salary: " . $row["salary"] . "<br><hr>";
}
} else {
echo "No records found!";
}
mysqli_close($conn);
?>
Ans.
Here's a simple PHP program to connect PHP with MySQL using the mysqli extension.
<?php
// Step 1: Set connection variables
$servername = "localhost"; // usually localhost
$username = "root"; // default for XAMPP
$password = ""; // default password is blank
$dbname = "test_db"; // name of your database
Ans,
✅ Definition:
The mysqli_connect() function is used to establish a connection between a PHP script and
a MySQL database.
Syntax:
Parameter Description
✅ Example:
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
Ans.
1. INT
Ex:
age INT;
2. VARCHAR(n)
Ex:
name VARCHAR(100);
3. DATE
Example: 2025-04-05
Ex:
dob DATE;
4. FLOAT / DOUBLE
Ex:
price FLOAT;