PHP QB 2
PHP QB 2
syntax:
class classname{
//code
}
=========================================================================
2. How to create an object in PHP?
Syntax:
Example:
$myCar = new Car();
=========================================================================
3. Differentiate between `this` and `self` keyword in PHP.
=========================================================================
4. Explain the `this` keyword with an example.
The this keyword refers to the current object and is used to access instance
properties and methods inside a class.
Example:
<?php
class Car {
public $brand;
=========================================================================
Example:
<?php
class Car {
public $brand;
public function __construct($name) {
$this->brand = $name;
}
=========================================================================
6. Explain destructor with an example.
A destructor is a special method in PHP that is automatically called when an object
is destroyed or goes out of scope. It is defined using __destruct().
Example:
<?php
class Car {
public $brand;
=========================================================================
<?php
class Car {
public $brand;
public function __construct($name) {
$this->brand = $name;
}
=========================================================================
8. Differentiate between constructor and destructor.
Usage Used to set up initial values Used for cleanup tasks like closing
files or connections
=========================================================================
Inheritance is a feature in PHP where a child class inherits properties and methods
from a parent class. It helps in code reuse and allows modifications in the child
class without changing the parent class.
Syntax:
class ParentClass {
// Properties and Methods
}
Example:
<?php
class Vehicle {
public function getMessage() {
return "This is a vehicle.";
}
}
=========================================================================
10. Describe an abstract class with a suitable example.
An abstract class cannot be instantiated and must have at least one abstract
method that is defined in child classes.
Example:
<?php
abstract class Vehicle {
abstract public function move();
}
Methods Can have both abstract & Only abstract methods (PHP 7.4
normal methods and below)
=========================================================================
12. Describe method overloading in PHP.
Method overloading in PHP is achieved using the __call() method. It allows calling
methods that are not explicitly defined in the class.
Example:
<?php
class Demo {
public function __call($name, $arguments) {
return "Method '$name' called with " . count($arguments) . " arguments.";
}
}
Method overriding occurs when a child class redefines a method from its parent
class with the same name and parameters.
The method in the child class must have the same name, parameters, and visibility
as in the parent class.
Example:
<?php
class ParentClass {
public function show() {
return "This is the parent class.";
}
}
=========================================================================
14. What is introspection? Explain with a suitable example.
Introspection is the process of analyzing classes, objects, methods, and properties
at runtime.
It helps to dynamically check information about a class or object.
Example:
<?php
class Car {
public $brand = "Toyota";
public function drive() {
return "Driving...";
}
}
Output:
Class Name: Car
Array ( [0] => drive )
15. Explain the in-built function `class_exists()` in PHP introspection.
The class_exists() function in PHP checks whether a class is defined or not at
runtime. It is useful for checking class availability before using it to avoid errors.
Syntax:
class_exists(string $class_name, bool $autoload = true): bool
Example:
<?php
class Car {
public $brand = "Toyota";
}
if (class_exists("Car")) {
echo "Class Car exists!";
} else {
echo "Class Car does not exist.";
}
?>
=========================================================================
Example:
<?php
class Car {
public function start() {}
protected function stop() {}
private function engine() {} // Private method won't be listed
}
$methods = get_class_methods("Car");
print_r($methods);
?>
Output:
Array ( [0] => start [1] => stop )
=========================================================================
17. Describe shallow copy in PHP with a suitable example.
A shallow copy in PHP creates a new object but copies references of the properties
instead of duplicating them.
Shallow copy only copies references, not actual data
This means changes to nested objects or arrays in one copy also affect the other.
Example:
<?php
class Car {
public $brand;
}
echo $car1->brand;
?>
Output: Honda
=========================================================================
Example:
<?php
class Car {
public $brand;
echo $car1->brand;
?>
Output: Toyota
Data Visibility Data is visible in the URL. Data is hidden from the URL.
Security Less secure, as data can be seen. More secure, as data is not
exposed.
=========================================================================
A cookie is a small piece of data stored on the user's browser to track user
preferences or sessions.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Example:
<?php
setcookie("user", "John", time() + 3600, "/");
?>
=========================================================================
Lifetime Expires when the browser is closed Can persist even after the browser
(unless set manually) is closed
Security More secure as data is stored on the Less secure as data is stored on the
server client-side
Usage Used for storing sensitive user data Used for tracking user preferences
like login info
=========================================================================
22. How can we destroy a cookie?
=========================================================================
23. How to register a variable in a PHP session?
To register a variable in a PHP session, follow these steps:
Example:
<?php
session_start(); // Start the session
$_SESSION["username"] = "JohnDoe"; // Register a session variable
To connect a PHP script with a MySQL database, we use the mysqli or PDO
extension. The basic steps are:
1. Establish a connection using mysqli_connect().
2. Check if the connection is successful.
3. Perform database operations (SELECT, INSERT, UPDATE, DELETE).
4. Close the connection.
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydb";
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
=========================================================================
25. Explain any one operation in PHP with a MySQL database: `SELECT`, `INSERT`,
`UPDATE`, or `DELETE`.
Example:
<?php
$conn = mysqli_connect("localhost", "root", "", "my_database");
$result = mysqli_query($conn, "SELECT name FROM customers");
=========================================================================
26. Explain any one form control with a suitable example. (1) Textfield (2)
Checkbox (3) Listbox
A Textfield is an input box where users can enter text. It is created using the <input
type="text"> element in an HTML form.
A text field is created with name="username".
When the user submits the form, PHP retrieves the value using
$_POST["username"].
The entered name is displayed after submission.
Example:
<!DOCTYPE html>
<html>
<body>
<form method="post">
Name: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Entered Name: " . $_POST["username"];
}
?>
</body>
</html>
=========================================================================
27. How does the form information get from the browser to the server?
When a user fills out a form in a web browser and submits it, the form data is sent
to the server using either the GET or POST method.
=========================================================================
28. Create a Customer form with fields like Customer Name, Address, Mobile No,
Item Purchased, and Amount using different form input elements, and display
the user-inserted values in a new PHP form. (Display values in the new form)
(customerForm.html)
(display.php)
<?php
echo "Customer Name: " . $_POST["name"] . "<br>";
echo "Address: " . $_POST["address"] . "<br>";
echo "Mobile: " . $_POST["mobile"] . "<br>";
echo "Item: " . $_POST["item"] . "<br>";
echo "Amount: " . $_POST["amount"] . "<br>";
?>
=========================================================================
29. Create an Employee form with fields like Employee Name, Address, Mobile
No, Date of Birth, Post, and Salary using different form input elements, and
display the user-inserted values in the same PHP form.
(Display values in the same form)
<form method="post">
Name: <input type="text" name="name"><br>
Address: <input type="text" name="address"><br>
Mobile No: <input type="text" name="mobile"><br>
DOB: <input type="date" name="dob"><br>
Post: <input type="text" name="post"><br>
Salary: <input type="text" name="salary"><br>
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Employee Name: " . $_POST["name"] . "<br>";
echo "Address: " . $_POST["address"] . "<br>";
echo "Mobile: " . $_POST["mobile"] . "<br>";
echo "DOB: " . $_POST["dob"] . "<br>";
echo "Post: " . $_POST["post"] . "<br>";
echo "Salary: " . $_POST["salary"] . "<br>";
}
?>
30. Write a PHP program that demonstrates form elements (input elements).
<form method="post">
Name: <input type="text" name="name"><br>
Age: <input type="number" name="age"><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br>
Hobbies:
<input type="checkbox" name="hobbies[]" value="Reading"> Reading
<input type="checkbox" name="hobbies[]" value="Sports"> Sports<br>
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Name: " . $_POST["name"] . "<br>";
echo "Age: " . $_POST["age"] . "<br>";
echo "Gender: " . $_POST["gender"] . "<br>";
if (!empty($_POST["hobbies"])) {
echo "Hobbies: " . implode(", ", $_POST["hobbies"]) . "<br>";
}
}
?>