0% found this document useful (0 votes)
5 views

Mid 1 Question With Answer (1)

The document provides a comprehensive overview of PHP programming concepts, including differences between echo and print, magic constants, loops, data types, operators, and object-oriented programming principles such as classes, objects, constructors, and inheritance. It includes examples and syntax for various PHP functionalities, along with explanations of key terms like polymorphism, encapsulation, and abstract classes. The content is structured as preparation questions for a midterm examination in a computer engineering course.

Uploaded by

hetthakor011
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)
5 views

Mid 1 Question With Answer (1)

The document provides a comprehensive overview of PHP programming concepts, including differences between echo and print, magic constants, loops, data types, operators, and object-oriented programming principles such as classes, objects, constructors, and inheritance. It includes examples and syntax for various PHP functionalities, along with explanations of key terms like polymorphism, encapsulation, and abstract classes. The content is structured as preparation questions for a midterm examination in a computer engineering course.

Uploaded by

hetthakor011
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

N.G.

PATEL POLYTECHNIC COLLAGE ISROLI-AFVA


COMPUTER ENGINEERING DEPARTMENT
SUB :- IWD(4340704) MID 1 PREPARATION QUESTIONS
LECTURER NAME :- B.P.PATEL

Q-1 Give difference between echo and print.


Echo Print

Echo accepts multiple arguments separated by commas. Print does not accept multiple arguments.

Echo can display outputs of multiple comma-separated Print can only display strings.
strings.

Echo can be used with or without parentheses. Print can also be used with or without
parentheses.

Echo does not return any value. Print always returns an integer value of 1.
Echo performs faster compared to Print. Print performs slower compared to Echo.

Q-2 list and define magic constants available in PHP.


• Magic constants are the predefined constants in PHP which get changed on the basis of their use.
• They start with double underscore (__) and ends with double underscore.
• They are similar to other predefined constants but as they change their values with the context, they are
called magic constants.
• There are nine magic constants in PHP. In which eight magic constants start and end with double
underscores (__).
1. __LINE__
2. __FILE__
3. __DIR__
4. __FUNCTION__
5. __CLASS__
6. __TRAIT__
7. __METHOD__
8. __NAMESPACE__
9. ClassName::class

Q-3 Describe FOREACH loop in PHP with Example.


The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next element will be
processed.
Syntax
foreach (array as value)
{
code to be executed;
}
Example
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
PREPARED BY:-B.P.PATEL
{
echo "Value is $value ";
}
?>
Q-4 Differentiate between Dynamic web pages and Static web pages.
Static Web Page Dynamic Web Page

In static web pages, Pages will remain same until In dynamic web pages, Content of pages are different
someone changes it manually. for different visitors.

Static Web Pages are simple in terms of


Dynamic web pages are complicated.
complexity.

In static web pages, Information are change In dynamic web page, Information are change
rarely. frequently.

Static Web Page takes less time for loading than


Dynamic web page takes more time for loading.
dynamic web page.

In Static Web Pages, database is not used. In dynamic web pages, database is used.

Static web pages are written in languages such Dynamic web pages are written in languages such as:
as: HTML, JavaScript, CSS, etc. CGI, AJAX, ASP, ASP.NET, etc.

Static web pages does not contain any Dynamic web pages contains application program for
application program . different services.

Static web pages require less work and cost in Dynamic web pages require comparatively more
designing them. work and cost in designing them.

Q-5 Write a PHP program to print 1 to 10 numbers using for and while loop statement.

<?php
echo "Numbers from 1 to 10 using for loop:<br>";
for ($i = 1; $i <= 10; $i++)
{
echo $i . " ";
}
echo "<br><br>";
echo "Numbers from 1 to 10 using while loop:<br>";
$i = 1;
while ($i <= 10)
{
echo $i . " ";
$i++;
}
?>

PREPARED BY:-B.P.PATEL
Output:-

Q-6 List data types and operators in PHP.


Variables can store data of different types, and different data types can do different things.
• PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
❖ PHP Operators can be categorized in following forms:
• Arithmetic Operators
• Assignment Operators
• Bitwise Operators
• Comparison Operators
• Incrementing/Decrementing Operators
• Logical Operators
• String Operators
• Array Operators
• Type Operators
• Execution Operators
• Error Control Operators
• We can also categorize operators on behalf of operands.
They can be categorized in 3 forms:
• Unary Operators: works on single operands such as ++, -- etc.
• Binary Operators: works on two operands such as binary +, -, *, /
Q-7 List all PHP operators. Define Bitwise operator with example
Arithmetic Operators:
Operator Description Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division (returns a floating-point number) x/y
// Floor division (returns the integer quotient) x // y
% Modulus (returns the remainder of division) x%y
** Exponentiation (raises a number to a power) x ** y
PREPARED BY:-B.P.PATEL
Comparison Operators:
Operator Description Example

== Equal to x == y

!= Not equal to x != y

< Less than x<y

> Greater than x>y

<= Less than or equal to x <= y

>= Greater than or equal to x >= y

Logical Operators:
Operator Description Example
and Logical AND (returns True if both operands are True) x and y
or Logical OR (returns True if at least one operand is True) x or y
not Logical NOT (returns the opposite of the operand) not x
Bitwise Operators:
Operator Description Example
& Bitwise AND x&y
` ` Bitwise OR
^ Bitwise XOR x^y
~ Bitwise NOT ~x
<< Left shift x << y
>> Right shift x >> y
Membership Operators:
Operator Description Example
in Checks if a value is present in a sequence x in sequence
not in Checks if a value is not present in a sequence x not in sequence

Identity Operators:
Operator Description Example
is Checks if two objects refer to the same memory location x is y
is not Checks if two objects refer to different memory locations x is not y

PREPARED BY:-B.P.PATEL
Assignment Operators:
Operator Description Example
= Assigns a value to a variable x=y
+= Adds a value to a variable x += y
-= Subtracts a value from a variable x -= y
*= Multiplies a variable by a value x *= y
/= Divides a variable by a value x
/= y
//= Floor divides a variable by a value x //= y
%= Calculates the modulus of a variable and a value x %= y
**= Raises a variable to a power x **= y
<<= Left shifts a variable by a number of bits x <<= y
>>= Right shifts a variable by a number of bits x >>= y

Bitwise operators are used to perform operations on individual bits of integer values. They are often
used in low-level programming and optimization tasks.
Examples:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
# Bitwise AND
result = a & b
print(result)
Output: 1 (Binary: 0001)
# Bitwise OR
result = a | b
print(result)
Output: 7 (Binary: 0111)

# Bitwise XOR
result = a ^ b
print(result)
Output: 6 (Binary: 0110)

# Bitwise NOT
result = ~a
print(result)
Output: -6 (Binary: 1010)

# Left shift
result = a << 2
print(result)
Output: 20 (Binary: 010100)

# Right shift
result = a >> 2

PREPARED BY:-B.P.PATEL
print(result)
Output: 1 (Binary: 0001)
Q-8 Define following terms:
1. Class
• Class is a collection of objects of similar type.
• Object with same properties and operations form a group known as class.
• Class contains data member and data function.
• In a class, variables are called properties (data member) and data functions are called methods.
• Example: Suppose class name is car, then we can create three individual objects with the name
of: Mercedes, Bmw, and Audi.

2. Object
• An object is an instance of a class.
• Object is one type of class variable.
• An object is represented as its properties (attributes) and the operation performed on it.
• We can create multiple objects from a class. Each object has all the properties and methods
defined in the class, but they will have different property values.
• Example: suppose Student is a class which contains two objects s1 and s2 with properties
marks and percentage.
3. Constructor
• constructor is a method defined inside a class is called automatically at the time of creation of
object.
• Purpose of a constructor method is to initialize the object.
• A constructor is a public method which is named as __construct
• Syntax:
function __construct()
{
// initialize the object and its properties by assigning values
}
4.Polymorphism
• Polymorphism means to use the same thing for different purpose.
• It contains the same function name and that function performs different tasks according to the
number of arguments.
5. Encapsulation
• The wrapping up of data and methods into a single unit (called class) is known as
encapsulation.
• Encapsulation is a protection mechanism for the data members and methods present inside the
class.
• In the encapsulation technique, we are restricting the data members from access to outside
world end-user.
• In PHP, encapsulation utilized to make the code more secure and robust.
• Using encapsulation, we are hiding the real implementation of data from the user and also
does not allow anyone to manipulate data members except by calling the desired operation.
6. Overloading
• Overloading means to use the same thing for different purpose.
• It contains the same function name and that function performs different tasks according to the
number of arguments.
7. function overriding:
• The two methods with the same name and same parameter is called overriding.
• Both parent and child classes should have same function name with and number of arguments.
• It is used to replace parent method in child class. The purpose of overriding is to change the
behavior of parent class method.
PREPARED BY:-B.P.PATEL
Q-9 How to create class and object in PHP. Explain with example.
A class is defined by using the class keyword, followed by the name of the class and a pair of curly
braces ({}). All its properties and methods go inside the braces:
Syntax:
<? php
Class class name
{
// codes go here
}
?>
Object:
• Objects of a class are created using the new keyword.
• We can create multiple objects from a class.
• Each object has all the properties and methods defined in the class, but they will have different
property values.
Syntax:
$Objname= new clas name();
<?php
class Add
{
protected $a;
protected $b;
function set_no($a,$b)
{
$this->a = $a; $this->b = $b;
}
function sum()
{
return $this->a + $this->b;
}
}
$no = new Add();
$no->set_no(10,20);
echo $no->sum();
echo "<br> ";
?>
Output:-30

Q-10 Describe the cloning of object with suitable example.


• The clone keyword is used to create a copy of an object.
• When an object is cloned, PHP will perform a shallow copy of all of the object’s properties.
Syntax:
$copy_object_name = clone $object_to_be_copied;
• The clone keyword creates a shallow copy. Change in value of property doesn't reflect in cloned
object.
• cloned object have different values than original object but original and referenced object created by
using ‘=’ operator have same value.
<?php
class Student
{
public $name;
public $sem;
PREPARED BY:-B.P.PATEL
public $spi;
}
$obj = new Student ();
$copy = clone $obj;
$obj->name = "abc";
$obj->sem = "3";
$obj->spi = "9.2";
$copy->name = "xyz";
$copy->sem = "3";
$copy->spi = "8.7";
echo $obj->name .$obj-> sem .$obj->spi."<br>" ;
echo $copy->name. $copy-> sem. $copy->spi."<br>";
Output:-

Q-11 Explain the use of final keyword in PHP with proper example
• The final keyword is used only for methods and classes.
• if we declare class method as a Final then that method cannot be override by the child class.
• Same as method if we declare class as a Final then that class cannot be extended any more.
• A final class can contain final as well as non final methods. But there is no use of final methods in
class when class is itself declared as final because inheritance is not possible.
Example (method as final)
<?php
class base
{
final public function display()
{
echo "Base class..";
}
}
class derived extends base
{
public function display()
{
echo "derived class";
}
}
$obj = new derived();
$obj->display();
?>
Output:
Error
Q-12Write a PHP code to demonstrate multilevel inheritance.
<?php

class Grandparent
{
public function familyHistory()
{
PREPARED BY:-B.P.PATEL
echo "This is the grandparent's family history.<br>";
}
}
class Parent1 extends Grandparent
{
public function parentTraits()
{
echo "This is a trait inherited from the parent.<br>";
}
}
class Child extends Parent1
{
public function childTalent()
{
echo "This is the child's unique talent.<br>";
}
}
$childObject = new Child();
$childObject->familyHistory();
$childObject->parentTraits();
$childObject->childTalent();
?>
Output:-

Q-13 Describe Constructor in PHP with suitable example.


Constructors:
• constructor is a method defined inside a class is called automatically at the time of creation of object
• Purpose of a constructor method is to initialize the object.
• A constructor is a public method which is named as __construct
Syntax:
function __construct()
{
// initialize the object and its properties by assigning values
}
Constructor types:
• Default Constructor: It has no parameters, but the values to the default constructor can be passed
dynamically.
• Parameterized Constructor: It takes the parameters, and also you can pass different values to the data
members.
• Copy Constructor: It accepts the address of the other objects as a parameter.
Example:-
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age)

PREPARED BY:-B.P.PATEL
{
$this->name = $name;
$this->age = $age;
}

public function displayInfo()


{
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age . "<br>";
}
}
$person1 = new Person("swara", 07);
$person1->displayInfo();

$person2 = new Person("bhavika", 30);


$person2->displayInfo();
?>
Output:-

Q-14 Describe Abstract Class with suitable example.


An abstract class is a mix between an interface and a class. It can be define functionality as well as interface.
• Classes extending an abstract class must implement all of the abstract methods defined in the
abstract class.
• An abstract class is declared the same way as classes with the addition of the 'abstract' keyword.
• Abstract classes and methods are when the parent class has named method, but need its child class
to fill out the tasks.
• An abstract class is a class that contains at least one abstract method. An abstract method is method
that is declared , but not implemented in the code.
Syntax:
<?php
abstract class ParentClass
{
abstract public function someMethod1();
abstract public function someMethod2($name,$color);
abstract public function someMethod3():string;
}
?>
Example:-
PREPARED BY:-B.P.PATEL
<?php
abstract class Base
{
abstract function display();
}
class Derived extends Base
{
function display()
{
echo "Derived class";
}
}
$b1 = new Derived;
$b1->display();
?>
Output:-

Q-15 Write a PHP code to demonstrate method overriding.


<?php
class Base
{
function display()
{
echo "Base class function :display <br>";
}

function demo()
{
echo "Base class function:demo<br>";
}
}
class Derived extends Base
{
function demo()
{
echo "Derived class function:demo<br>";
}
}
$ob = new Base;
$ob->demo();
$ob->display();
$ob1 = new Derived;
PREPARED BY:-B.P.PATEL
$ob1->demo();
$ob1->display();
?>
Output:-

Q-16 Differentiate between GET and POST method.


GET Method POST Method
Using GET method data is sent from one page Using POST method data is sent from onepage to
toother in the URL other within the body of the HTTP request

The GET method, appends name/value pairs to POST method packages the name/value pair inside
theURL body of HTTP request, which makes fora clean URL

The length of URL is limited, so it works if POST method imposes no size limitations onforms
thereare few parameters. output.

It is insecure because parameters passed on the It is secure because submitted data are passed
URL are visible in address field of browser. through HTTP handler.
It can’t be used to send binary data, like images Using POST method can be used to send
orword documents, to server. ASCII as well as binary data.
The data send by POST method can be
accessed using $_POST superglobal variable

Q-17 Explain method and action attributes of FORM element

1. method Attribute

• Purpose: Specifies the HTTP method (like GET or POST) used to send form data to the server.
• Common Values:
o GET:
▪ Data is appended to the URL as query parameters (visible in the browser address bar).
▪ Limited data size due to URL length restrictions.
▪ Generally not suitable for sensitive data.
o POST:
▪ Data is sent in the message body of the HTTP request, not visible in the URL.
▪ Can handle larger amounts of data and is more secure for sensitive information.

2. action Attribute

• Purpose: Defines the URL of the script or page on the server that will process the form data.
• Example:
o If action="process.php", the form data will be sent to the process.php file on the server.

PREPARED BY:-B.P.PATEL
<form action="process.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
Q-17 Explain session? Explain how to create access and destroy a session with suitable example.
What is a Session?
In web development, a session is a temporary storage mechanism that servers use to maintain information
about a specific user's interaction with a website during a single visit.
Think of it as a temporary container that holds data related to that particular user's session. This data can
include things like:
• User login status: Whether they are logged in or not.
• User preferences: Language, theme, etc.
• Items added to a shopping cart.
• Tracking user activity within the website.
How Sessions Work in PHP
1. Session Start:
o session_start(); This function initializes the session and makes session variables
accessible.
2. Data Storage:
o $_SESSION is a superglobal array in PHP that allows you to store session data.
▪ Example: $_SESSION['username'] = "john_doe";
3. Data Retrieval:
o Access session data using the $_SESSION array:
▪ Example: echo "Welcome, " . $_SESSION['username'];
4. Session Destruction:
o session_destroy(); This function deletes all session data associated with the current user.
Example (PHP)
<?php
session_start();
if(isset($_SESSION['username']))
{
echo "Welcome, " . $_SESSION['username'] . "!";
} else {
header("Location: login.php");
exit();
}
$_SESSION['user_id'] = 123;
$userId = $_SESSION['user_id'];
echo "User ID: " . $userId;
session_destroy();
?>
Q-18 Define following form element
i) Upload
• Upon form submission, the selected files are transmitted to the server along with other form data.
ii) Dropdown
• This is like combobox control of Visual basic. Dropdown list is used to select one option from given
list of choice.
iii) Checkbox.
• It allows you to represent list of options to the users from which user can select none, one or more
than one options at a time.
• Thus it useful when you want to represent various choices to user from which he/she can select
choices as per his/her requirement.
• It displays as small square on web page
PREPARED BY:-B.P.PATEL
Syntax : <input type=”checkbox” name=”Name” value=”Value” [checked]> Text </input>
Text TYPE: Indicates type of input element. So it is checkbox.
NAME: Variable name passed to application.
VALUE: Data associated with variable name
iv) Radio box
• It allows you to represent list of options to the users from which user can select only one options at a
time.
• Thus it useful when you want to represent various choices to user from which he/she can select only
one choice as per his/her requirement.
• It displays as small circle on web page
v) Date
• It defines a date picker. The resulting value includes the year, month, and day
• Syntax: <input type="date">
vi) Color
• It defines a color picker. The default value is #000000 (black).
• Syntax: <input type="color">

Q-19 Write a PHP script to store, retrieve and destroy SESSION data of user.
Session.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["User"]="Bhavika";
echo"Session information are set successfully.<br/>";
?>
<a href="session2.php">Vist next page</a>
</body>
</html>
Output:-

Session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is : ".$_SESSION["User"];
?>
</body>
</html>
Output:-

PREPARED BY:-B.P.PATEL
Coun.php
<?php
session_start();
if(!isset($_session['counter']))
{
$_session['counter']=1;
}
else
{
$_session["counter"]++;
}
echo"Page views : ".$_session["counter"]."<br>"
?>
<a href="des.php">View next page</a>
Output:-

Des.php
<?php
session_start();
session_destroy();
?>
Output:

PREPARED BY:-B.P.PATEL
Q-20 Differentiate COOKIE and SESSION.

Cookies Session

Cookies are client-side files on a local Sessions are server-side files that contain user
computer that hold user information. data.

Cookies end on the lifetime set by the When the user quits the browser or logs out of
user. the programmed, the session is over.

It can only store a certain amount of


It can hold an indefinite quantity of data.
info.

We can keep as much data as we like within a


The browser’s cookies have a session, however there is a maximum memory
maximum capacity of 4 KB. restriction of 128 MB that a script may consume
at one time.

Because cookies are kept on the local


To begin the session, we must use the session
computer, we don’t need to run a
start() method.
function to start them.

Session are more secured compare than


Cookies are not secured.
cookies.

Cookies stored data in text file. Session save data in encrypted form.

Cookies stored on a limited data. Session stored a unlimited data.

In PHP, to get the data from Cookies , In PHP , to get the data from Session,
$_COOKIES the global variable is used $_SESSION the global variable is used

Q-21 Write a PHP code to demonstrate storing and retrieving information from cookies.
<?php
$cookie_name = "user";
$cookie_value = "Engineering";
setcookie($cookie_name, $cookie_value);
?>

<html>
<body>
<?php
if(isset($_COOKIE[$cookie_name]))
{
echo "Cookie named : ".$cookie_name." is set successfully."."<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
else
PREPARED BY:-B.P.PATEL
{
echo "Cookie is not set succcessfully.";;
}
?>
</body>
</html>

Output:-

Q-22 List form controls available in PHP. Explain anyone with proper example.
• Text Box, Textarea, List Box, Dropdown, Check Box, Radio Box, Buttons, Upload, color, date etc.
Introduction to Forms:
• Whenever you are going to design a page, which can accept information from users through various
input fields.
• A form can contain input elements like
1. Textfield
2. Textarea
3. Checkboxes
4. Radio-buttons
5. Drop-down list
6. Submit buttons etc..
• Forms are used to pass data to a server.
• The FORM element has no formatting attributes. Input Elements: Input elements are used to get
input from user in various format.

• 1. Using Textbox: User can enter text or single line using textbox
Syntax:<input type="text" name="Textname" value=”defaultvalue”>
Example:
<form>
Enter your Name:<input type="text" name="txtName">
</form>

Q-23 Write a PHP program that displays an HTML form with following input fields:
1. Name
2. Email
3. Password
4. Gender
5. Hobbies
6. Country
7. Languages and
8. Submit. Then, use $_POST superglobal to retrieve the values of input fields and print them.
PREPARED BY:-B.P.PATEL
<!DOCTYPE html>
<html>
<head>
<title>User Information Form</title>
</head>
<body>

<h2>User Information</h2>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$gender = $_POST["gender"];
$hobbies = isset($_POST["hobbies"]) ? implode(", ", $_POST["hobbies"]) : "None";
$country = $_POST["country"];
$languages = isset($_POST["languages"]) ? implode(", ", $_POST["languages"]) : "None";

// Display retrieved data


echo "<h2>Submitted Information:</h2>";
echo "<p>Name: " . $name . "</p>";
echo "<p>Email: " . $email . "</p>";
echo "<p>Password: " . $password . "</p>";
echo "<p>Gender: " . $gender . "</p>";
echo "<p>Hobbies: " . $hobbies . "</p>";
echo "<p>Country: " . $country . "</p>";
echo "<p>Languages: " . $languages . "</p>";
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">


<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>

<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="Male"> Male
<input type="radio" id="female" name="gender" value="Female"> Female
<input type="radio" id="other" name="gender" value="Other"> Other<br><br>

<label for="hobbies">Hobbies:</label><br>
<input type="checkbox" name="hobbies[]" value="Reading"> Reading<br>
<input type="checkbox" name="hobbies[]" value="Music"> Music<br>
<input type="checkbox" name="hobbies[]" value="Sports"> Sports<br>
<input type="checkbox" name="hobbies[]" value="Travel"> Travel<br><br>

PREPARED BY:-B.P.PATEL
<label for="country">Country:</label>
<select id="country" name="country">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="India">India</option>
</select><br><br>

<label for="languages">Languages:</label><br>
<input type="checkbox" name="languages[]" value="English"> English<br>
<input type="checkbox" name="languages[]" value="Spanish"> Spanish<br>
<input type="checkbox" name="languages[]" value="French"> French<br>
<input type="checkbox" name="languages[]" value="German"> German<br><br>

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


</form>

</body>
</html>

PREPARED BY:-B.P.PATEL

You might also like