0% found this document useful (0 votes)
6 views19 pages

PHP QB 2

The document provides a comprehensive guide on PHP programming, covering topics such as class creation, object instantiation, constructors, destructors, inheritance, and method overloading/overriding. It also explains database connectivity, form handling, cookies, sessions, and the differences between GET and POST methods. Additionally, it includes examples for each concept to illustrate their usage in PHP.

Uploaded by

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

PHP QB 2

The document provides a comprehensive guide on PHP programming, covering topics such as class creation, object instantiation, constructors, destructors, inheritance, and method overloading/overriding. It also explains database connectivity, form handling, cookies, sessions, and the differences between GET and POST methods. Additionally, it includes examples for each concept to illustrate their usage in PHP.

Uploaded by

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

1. How to create a class in PHP?

In PHP, you can create a class using the class keyword.

syntax:
class classname{
​ //code
}

=========================================================================
2. How to create an object in PHP?

In PHP, you create an object using the new keyword.

Syntax:

Objectname = new classname();

Example:
$myCar = new Car();

=========================================================================
3. Differentiate between `this` and `self` keyword in PHP.

Keyword this self

Usage Refers to the current object Refers to the current class

Accesses Instance properties & methods Static properties & methods

Syntax $this->property or self::$property or self::method()


$this->method()

Works Non-static members Static members


With

=========================================================================
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;

public function setBrand($name) {


$this->brand = $name; // Refers to the current object
}

public function getBrand() {


return $this->brand;
}
}

$myCar = new Car();


$myCar->setBrand("Toyota");

echo $myCar->getBrand(); // Output: Toyota


?>

=========================================================================

5. Explain constructor with an example.


A constructor is a special function inside a class that is automatically called when
an object is created. In PHP, the constructor method is named __construct().

Example:
<?php
class Car {
public $brand;
public function __construct($name) {
$this->brand = $name;
}

public function getBrand() {


return $this->brand;
}
}

$myCar = new Car("Toyota");


echo $myCar->getBrand();
?>

=========================================================================
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;

public function __construct($name) {


$this->brand = $name;
echo "Car created: " . $this->brand . "<br>";
}

public function __destruct() {


echo "Car destroyed: " . $this->brand;
}
}
$myCar = new Car("Toyota");
?>

=========================================================================

7. Explain parameterized constructor with a suitable example.

A parameterized constructor is a constructor that accepts arguments to initialize


object properties when an object is created.
Example:

<?php
class Car {
public $brand;
public function __construct($name) {
$this->brand = $name;
}

public function getBrand() {


return $this->brand;
}
}
$myCar = new Car("Toyota");
echo $myCar->getBrand();
?>

=========================================================================
8. Differentiate between constructor and destructor.

Feature Constructor (__construct()) Destructor (__destruct())

Purpose Initializes object properties Cleans up resources when an


object is destroyed

Execution Called automatically when an Called automatically when an


object is created object is no longer needed

Arguments Can accept parameters Does not take parameters


(Parameterized Constructor)

Usage Used to set up initial values Used for cleanup tasks like closing
files or connections

=========================================================================

9. What is inheritance? Explain with syntax and a suitable example.

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
}

class ChildClass extends ParentClass {


// Inherits properties & methods of ParentClass
}

Example:
<?php
class Vehicle {
public function getMessage() {
return "This is a vehicle.";
}
}

class Car extends Vehicle {}

$myCar = new Car();


echo $myCar->getMessage();
?>

=========================================================================
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();
}

class Car extends Vehicle {


public function move() {
return "Car is moving";
}
}

$myCar = new Car();


echo $myCar->move();
?>
11. Differentiate between an abstract class and an interface.

Feature Abstract Class Interface

Methods Can have both abstract & Only abstract methods (PHP 7.4
normal methods and below)

Properties Can have properties (variables) Cannot have properties

Keyword Used abstract class interface

Implementation Use extends in child class Use implements in class

Multiple Not supported Supported (a class can implement


Inheritance multiple interfaces)

=========================================================================
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.";
}
}

$obj = new Demo();


echo $obj->test(10, 20);
?>
Output: Method 'test' called with 2 arguments.
=========================================================================

13. Describe method overriding in PHP with a suitable example.

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.";
}
}

class ChildClass extends ParentClass {


public function show() {
return "This is the child class.";
}
}

$obj = new ChildClass();


echo $obj->show();
?>

Output: This is the child 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.

Common Introspection Functions in PHP:

●​ get_class($obj): Gets the class name of an object.​

●​ get_methods($class): Returns all methods of a class.​

●​ get_class_methods($class): Lists all public methods of a class.​

●​ get_object_vars($obj): Returns properties of an object.

Example:

<?php
class Car {
public $brand = "Toyota";
public function drive() {
return "Driving...";
}
}

$obj = new Car();

echo "Class Name: " . get_class($obj) . "<br>";


print_r(get_class_methods($obj));
?>

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.";
}
?>

=========================================================================

16. Explain the in-built function `get_class_methods()` in PHP introspection.

The get_class_methods() function returns an array of all public and protected


methods of a given class.
It is useful for inspecting available methods of a class at runtime.

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;
}

$car1 = new Car();


$car1->brand = "Toyota"; // Assigning brand directly

$car2 = $car1; // Shallow copy


$car2->brand = "Honda"; // Changes affect both objects

echo $car1->brand;
?>

Output: Honda

=========================================================================

18. Describe deep copy in PHP with a suitable example.

A deep copy creates a completely independent duplicate of an object, including all


nested objects or arrays. Changes in the copied object do not affect the original.

Example:
<?php
class Car {
public $brand;

public function __construct($brand) {


$this->brand = $brand;
}
}

$car1 = new Car("Toyota");


$car2 = clone $car1; // Deep copy using clone

$car2->brand = "Honda"; // Changing $car2 does NOT affect $car1

echo $car1->brand;
?>

Output: Toyota

19. Differentiate between GET and POST methods.


Feature GET Method POST Method

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.

Data Length Limited by URL length. No size limit for data.

Usage Used for retrieving data. Used for sending sensitive or


large data.

Bookmarking Can be bookmarked. Cannot be bookmarked.

=========================================================================

20. Define a cookie and explain the `set_cookie()` function in PHP.

A cookie is a small piece of data stored on the user's browser to track user
preferences or sessions.

The setcookie() function in PHP is used to create a cookie.

Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);

Example:
<?php
setcookie("user", "John", time() + 3600, "/");
?>

=========================================================================

21. Differentiate between `session()` and `cookie()` functions in PHP.


Feature Session Cookie

Storage Stored on the server Stored on the user's browser

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?

A cookie can be deleted by setting its expiration time to a past time:


Example:
setcookie("user", "", time() - 3600, "/"); // Deletes the cookie

=========================================================================
23. How to register a variable in a PHP session?
To register a variable in a PHP session, follow these steps:

1.​ Start the session using session_start().


2.​ Store a variable in the $_SESSION superglobal array.

Example:
<?php
session_start(); // Start the session
$_SESSION["username"] = "JohnDoe"; // Register a session variable

echo "Session variable set: " . $_SESSION["username"];


?>
24. Explain MySQL database connectivity with a suitable example.

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";

$conn = mysqli_connect($servername, $username, $password, $database);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";


mysqli_close($conn);
?>

=========================================================================
25. Explain any one operation in PHP with a MySQL database: `SELECT`, `INSERT`,
`UPDATE`, or `DELETE`.

The SELECT query is used to fetch data from a MySQL database.

Example:

<?php
$conn = mysqli_connect("localhost", "root", "", "my_database");
$result = mysqli_query($conn, "SELECT name FROM customers");

while ($row = mysqli_fetch_assoc($result)) {


echo "Name: " . $row["name"] . "<br>";
}
?>

=========================================================================
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.

If GET is used, form data is sent in the URL​

If POST is used, data is sent in the request body (more secure).

=========================================================================
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)

<form method="post" action="display.php">


Name: <input type="text" name="name"><br>
Address: <input type="text" name="address"><br>
Mobile No: <input type="text" name="mobile"><br>
Item Purchased: <input type="text" name="item"><br>
Amount: <input type="text" name="amount"><br>
<input type="submit">
</form>

(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>";
}
}
?>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy