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

php solved QB

The document is a chapterwise question bank covering various PHP concepts, including features, data types, operators, loops, and array manipulation. It provides examples of PHP scripts for tasks such as reversing a number, printing prime numbers, and using different types of loops. Additionally, it discusses the advantages of PHP, variable declaration rules, and control statements like if-else, break, and continue.

Uploaded by

mahekarekar20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

php solved QB

The document is a chapterwise question bank covering various PHP concepts, including features, data types, operators, loops, and array manipulation. It provides examples of PHP scripts for tasks such as reversing a number, printing prime numbers, and using different types of loops. Additionally, it discusses the advantages of PHP, variable declaration rules, and control statements like if-else, break, and continue.

Uploaded by

mahekarekar20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Chapterwise Question Bank

Chapter 01
1. State the features of php.
1. Web Application Features
2. Command line interface(CLI)
3.Built-in Modules
4.Object Oriented Programming (oop)
5.pre-compilation
6. Real Time acces monitoring
7. File I/O

2. List and explain any four data types of PHP.

Float : Floating point numbers represents numeric values with decimal points (real numbers)
or a number in
exponential form. The range of floating point values are 1.7E-308 to 1.7E+308. Example:
3.14, 0.25, -5.5, 2E-4, 1.2e2
String : A string is a sequence of characters. A string are declares using single quotes or
double quotes. Example:
“Hello PHP”, ‘Hello PHP’
Boolean : The Boolean data types represents two values, true(1) or false(0). Example:
$a=True
Object :
Objects are defined as instances of user defined classes that can hold both values and
functions. First we declare class
of object using keyword class. A class is a structure that contain properties(variables) and
methods(functions).

3. Write a PHP script to print reverse of a given number.


<?php
$num = 123;
$revnum = 0;
while ($num> 1)
{
$rem = $num % 10;
$revnum = ($revnum * 10) + $rem;
$num = ($num / 10);
}
echo "Reverse number of 123 is: $revnum";
?>
4. Write a PHP script to print prime numbers upto n numbers.
<?php
$count = 0 ;
$number = 2 ;
while ($count <20 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
$div_count++;
}
}
if ($div_count<3)
{
echo $number." , ";
$count=$count+1;
}
$number=$number+1;
}
?>

5. Explain Bitwise operators with example.(Any 4)


1. & (Bitwise AND) : This binary operator works on two operands. Bitwise AND
operator in PHP takes two numbers as
operands and does AND on every bit of two numbers. The result of AND is 1 only if
both bits are 1.
Example :
<?php
$a=5;
$b=3;
echo $a & $b;
echo "<br/>";
?>
Output : 1
(Binary representation of 5 is 0101 and 3 is 0011. Therefore, their bitwise & will be
0001)
2. | (Bitwise OR) :Bitwise OR operator takes two numbers as operands and does OR
on every bit of two numbers. The
result of OR is 1 any of the two bits is 1.
Example :
<?php
$a=5;
$b=3;
echo $a | $b;
echo "<br/>";
?>
Output : 7
( Binary representation of 5 is 0101 and 3 is 0011.Therefore their bitwise | will be
0111 )
3. ^ (Bitwise XOR ) : This is also known as Exclusive OR operator. Bitwise XOR
takes two numbers as operands and does
XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
Example :
<?php
$a=5;
$b=3;
echo $a ^ $b;
echo "<br/>";
?>
Output : 6
( Binary representation of 5 is 0101 and 3 is 0011. Therefore their bitwise ^ will be
0110)
4. ~ (Bitwise NOT) : This is a unary operator i.e. works on only one operand. Bitwise
NOT operator takes one number
and inverts all bits of it.
Example :
<?php
$a=5;
echo ~$a;
echo "<br/>";
?>
Output : 6
( Binary representation of 5 is 0101. Therefore the bitwise ~ of this will be 1010 )

6. Explain different loops in PHP with example


Explain different loops in PHP with example.
while loop: If the expression/condition specified with while
evaluates to true then the statements inside loop executes and
control is transferred back to expression/condition. The process of
evaluation and execution
Example:
<?php
$a=1;
while($a<=5)
{
echo " Iteration $a";
$a++;
}
?>
OR
Example:
<?php
$a=1;
while($a<=5):
echo " Iteration $a";
$a++;
endwhile;
?>
do-while loop:All the statements inside the loop executes for the
first time without checking any condition. The keyword „do‟ passes
the flow of control inside loop. After executing loop for the first
time, expression / condition is evaluated. If it evaluates to true then
all statements inside loop again executes and if it evaluates to false
then loop exits and flow of control passes to the next statement
placed outside the loop. The process of execution and evaluation
continues till expression / condition evaluates to true.
Example:
<?php
$a=1;
do
{
print("Iteration 1");
$a++;
}while($a<=0);
?>
for loop:It is used to execute same set of statements multiple times.
In for loop variable initialization, condition and increment /
decrement is placed in a single statement. Before starting first
iteration a variable is initialized to specified value. Then condition
is checked. If condition is true then statements inside the loop
executes and variable is incremented or decremented. Control then
passes to condition. If condition is false then control passes to the
statement placed outside the loop. The process of condition
checking, loop statement execution and increment /decrement
continues till condition is true.
Example :
<?php
for ($a=1;$a<=5;$a++)
{
echo("Iteration $a");
}
?>
for each loop: This loop works with arrays and is used to traverse
through values in an array. For each loop iteration, the value of the
current array element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element.
Example :
<?php
$arr=array("Apple","Banana","Orange");
foreach($arr as $fruit)
{
echo("$fruit");
}
?>
7. Describe advantage of PHP.
Simple and Easy : PHP is simple and easy to learn and code. The command functions
of PHP can easily learn and understood. The syntax is simple and flexible to use. −
Database : PHP is easily connected with the database and make the connection
securely with databases. It has a built-in module that is used to connect to the database
easily. Multiple databases can be integrated with PHP. −
Fast : PHP is known as the fastest Programming language as compared to another.
PHP applications can be easily loaded over the slow Internet and data speed. −
Support : This advantage of PHP has great online support and community, which
helps the new developers to help in writing the code and developing the web
applications. Compatible with servers like IIS and APACHE. −
Security : PHP frameworks built-in feature and tools make it easier to protect the web
applications from the outer attacks and security threats.

8. Write syntax of PHP.


<?php
echo ‘Hello world’;
?>

9. Write down rules for declaring PHP variable.


− A variable starts with the $ sign, followed by the name of the variable.
− A variable name must start with a letter or the underscore character.
− A variable name should not contain spaces. If a variable name is more than
one word, it should be separated with an underscore ($first_name), or with
capitalisation ($firstName)
− Variables used before they are assigned have default values.
− A variable name cannot start with a number.
− A variable name can only contain alpha-numeric characters (A-Z, a-z) and
underscores.
− Variable names are case-sensitive ($name and $NAME are two different
variables) − You able to use variable over and over again in your PHP script
after declaring it.
− Variables can, but do not need, to be declared before assignment. PHP
automatically converts the variable to the correct data type, depending on its
value.
− PHP variables are Perl-like.
− Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.

10. Write a PHP program to display numbers from 1-10 in a sequence using for loop.
PHP Code-
<?php
echo "Output<br>";
for($i=1;$i<=10;$i++)
{
echo "$i<br/>";
}
?>
Output
1
2
3
4
5
6
7
8
9
10

11. Describe the syntax of if-else control statement with example in PHP.
if-else control statement is used to check whether the
condition/expression is true or false. Ifthe expression / condition
evaluates to true then true block code associated with the if statement
is executed otherwise if it evaluates to false then false block of code
associated with else is executed.
Syntax:
if (expression/condition)
{
True code block;
}
else
{
False code block;
}
Example:
<?php
$a=30;
if ($a<20)
echo "variable value a is less than 20";
else
echo "variable value a is greater than 20";
?>
In the above example, variable a holds value as 30. Condition checks
whether the value of a is less than 20. It evaluates to false so the
output displays the text as ‘variable value a is greater than 20’

12. Explain the use of break and continue statements.


Break statement:-break keyword is used to terminate and transfer
the control to the next statement when encountered inside a loop or
switch case statement.
Syntax:
if (condition)
{ break; }
Example:
<?php
for ($a = 0; $a < 10; $a++)
{
if ($a == 7)
{
break; /* Break the loop when condition is true. */
}
echo "Number: $a <br>";
}
echo " Terminate the loop at $a number";
?>
ii)Continue Statement
It is used to skip the execution of a particular statement inside the
loops.
if (condition)
{ continue; }
Example:
<?php
for ($i = 0; $i< 10; $i++)
{
if ($i == 5)continue;
{
echo " $i<br>";
}}
echo "end";
?>
13. Explain Arithmetic operators with example. (Any 4)
Arithmetic operators are used in mathematical expression in the same way like
addition, subtraction, multiplication etc, that they are used in algebra.

<?php
$a = 20;
$b = 10;
echo "First number:$a <br/>";
echo "Second number:$b <br/>";
echo "<br/>";
$c = $a + $b;
echo "Addtion: $c <br/>";
$c = $a - $b;
echo "Substraction: $c <br/>";
$c = $a * $b;
echo "Multiplication: $c <br/>";
$c = $a / $b;
echo "Division: $c <br/>";
$c = $a % $b;
echo "Modulus: $c <br/>";
?>
Output
First number:20
Second number:10
Addtion: 30
Substraction: 10
Multiplication: 200
Division: 2
Modulus: 0
14. Explain logical operators with example. (Any 4)
Logical operators are basically used to operate with conditional statements and
expressions. Conditional statements are based on conditions. Conditional statement
can either be true or false.

<?php
$a = 20;
$b = 10;
if ($a == 20 and $b == 10)
echo "True <br/>";
if ($a == 20 or $b == 30)
echo "True <br/>";
if ($a == 20 xor $b == 5)
echo "True <br/>";
if ($a == 20 && $b == 10)
echo "True <br/>";
if ($a == 20 || $b == 20)
echo "True <br/>";
?>
Output :
True
True
True
True
True
Chapter 02

1. Write a program to create associative, multidimensional and indexed array in


PHP.
Indexed-
<?php
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
?>
Multidimensional-
<?php
// Defining a multidimensional array
$person = array(
array(
"name" => "Yogita K",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Manisha P.",
"mob" => "2584369721",
"email" => "[email protected]",
),
array(
"name" => "Vijay Patil",
"mob" => "9875147536",
"email" => "[email protected]",
)
);
// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
Output :
manisha P's email-id is: [email protected]
Vijay Patil's mobile no: 9875147536

Associative-
<?php
$capital = array("Mumbai" => "Maharashtra","Goa" => "Panaji", "Bihar" =>
"Patna");
print_r($capital);
echo"<br>";
echo "Mumbai is a capital of " .$capital ["Mumbai"];
?>
Output :
Array ( [Mumbai] => Maharashtra [Goa] => Panaji [Bihar] => Patna )
Mumbai is a capital of Maharashtra

2. List and explain any four maths functions in PHP.

3. Explain Anonymous or Lambda Function with example


There are times when you need to create a small localized throw-away function
consisting of a few lines for a
specific purpose, such as a callback. It is unwise to pollute the global namespace with
these kind of single use functions. For
such an event you can create anonymous or lambda functions using create_function
(). Anonymous functions allow the
creation of functions which have no specified name. An example is as follows :
Example 1 :
<?php
$str = "hello world!";
$lambda = create_function('$match', 'return "friend!";');
$str = preg_replace_callback('/world/', $lambda, $str);
echo $str ;
?>
Output :
hello friend!
4. Explain Unset functions with example
The unset() function is used to remove element from the array. The unset() function is
used to destroy any other
variable and same way use to delete any element of an array.
The unset () function accepts a variable name as parameter and destroy or unset that
variable.
Syntax :
void unset ($var,...);
Example 1 :
<?php
$course = array("CO", "IF", "EJ", "ME", "CE");
echo "<h2> Before deletion:</h2><br>";
echo "$course[0] <br>";
echo "$course[1] <br>";
echo "$course[2] <br>";
echo "$course[3] <br>";
echo "$course[4] <br>";
// unset command accepts 3rd index and thus removes the array element at
// that position
unset($course[3]);
echo "<h2> Before deletion:</h2><br>";
print_r($course);
echo "<h2> Delete entire array elements:</h2><br>";
unset($course); //delete all elements from an array
?>
Output :
Before deletion:
CO
IF
EJ
ME
CE
Before deletion:
Array ( [0] => CO [1] => IF [2] => EJ [4] => CE )
Delete entire array elements

5. Explain Any four sort functions with example. (Any 4)


Following are the Sorting Functions for Arrays in PHP :
1. sort(): sorts arrays in ascending order
2. rsort(): sorts arrays in descending order
3. asort(): sorts associative arrays in ascending order, according to the value
4. ksort(): sorts associative arrays in ascending order, according to the key
5. arsort(): sorts associative arrays in descending order, according to the value
6. krsort(): sorts associative arrays in descending order, according to the key

<?php
$num = array(40, 61, 2, 22, 13);
echo "Before Sorting:<br>";
$arrlen= count($num);
for($x = 0; $x < $arrlen; $x++)
{
echo $num[$x];
echo "<br>";
}
sort($num);
echo "After Sorting in Ascending order:<br>";
$arrlen= count($num);
for($x = 0; $x < $arrlen; $x++)
{
echo $num[$x];
echo "<br>";
}
echo "After Sorting in Descending order:<br>";
rsort($num);
$arrlen= count($num);
for($x = 0; $x < $arrlen; $x++)
{
echo $num[$x];
echo "<br>";
}
?>
Output :
Before Sorting:
40
61
2
22
13
After Sorting in Ascending order:
2
13
22
40
61
After Sorting in Descending order:
61
40
22
13
2
6. Explain PHP string functions with example. (Any 4)
7. Define function. How to define user defined function in PHP? Give example.
PHP functions are similar to other programming languages. A function is a piece of
code which takes one more input
in the form of parameter and does some processing and returns a value.
They are built-in functions but PHP gives you option to create your own functions
as well. A function will be executed
by a call to the function. You may call a function from anywhere within a page.
There are two parts which should be clear to you
o Creating a PHP Function
o Calling a PHP Function
It’s very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a
simple message on your browser when you will call it. Following example creates a
function called writeMessage()
and then calls it just after creating it.
A user-defined function declaration starts with the word function :
Syntax :
function functionName()
{
code to be executed;
}
Web Based Application Development using PHP (MSBTE) 2-27 Arrays, Functions
and Graphics
Example :
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage(){
echo "Welcome to PHP world!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
Output :
Welcome to PHP world
8. Write a PHP program to (i) Calculate length of string (ii) Count number of
words in the string
i) Calculate length of string
<?php
$str = 'Have a nice day ahead!';
echo "Input String is:".$str;
echo "<br>";
echo "Length of String str:".strlen($str);
// output =12 [including whitespace]
?>
ii) Count number of words in string
Solution1-
<?php
// PHP program to count number of
// words in a string
$str = " This is a string ";
// Using str_word_count() function to count number of words in a
string
$len = str_word_count($str);
// Printing the result
echo "Number of words in string : $len";
?>
Output:
Number of words in string : 4

OR
Solution 2:
<?php
// PHP program to count number of
// words in a string
$string = " This is a string ";
$str = trim($string);
while (substr_count($str, " ") > 0) {
$str = str_replace(" ", " ", $str);
}
$len = substr_count($str, " ")+1;
// Printing the result
echo "Number of words in string: $len";
?>
Output:
Number of words in string: 4
9. Define Array. State its types.
Arrays in PHP is a type of data structure that allows to store multiple elements of
similar data type under a single
variable thereby saving us the effort of creating a different variable for every data.
An array in PHP is actually an ordered map. A map is a type that associates values
to keys.
The arrays are helpful to create a list of elements of similar types, which can be
accessed using their index or key.
Suppose we want to store five names and print them accordingly. This can be easily
done by the use of five different
string variables. But if instead of five, the number rises to hundred, then it would be
really difficult for the user or
developer to create so much different variables. Here array comes into play and helps
us to store every element
within a single variable and also allows easy access using an index or a key.
An array is created using an array() function in PHP.
Types of Array :
There are basically three types of arrays in PHP :
1. Indexed or Numeric Arrays
2. Associative Arrays
3. Multidimensional Arrays

10. Explain two functions to scale the given image.


imagecopyresized() function : It is an inbuilt function in PHP which
is used to copy a rectangular portion of one image to another image
and resize it. dst_image is the destination image, src_image is the
source image identifier.
Syntax:
imagecopyresized(dst_image, src_image, dst_x, dst_y,src_x, src_y,
dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
src_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example:
imagecopyresized($d_image,$s_image,0,0,50,50,200,200,$s_width,
$s_height);
imagecopyresampled() function : It is used to copy a rectangular
portion of one image to another image, smoothly interpolating pixel
values thatresize an image.
Syntax:
imagecopyresampled(dst_image, src_image, dst_x, dst_y,src_x,
src_y, dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
ṇsrc_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example:
imagecopyresampled($d_image,$s_image,0,0,50,50,200,200,$s_widt
h,$s_height);

11. Write a program to display image in php.


<?php
$src = ImageCreateFromJPEG('php.jpg');
$width = ImageSx($src);
$height = ImageSy($src);
$x = $width/2;
$y = $height/2;
$dst = ImageCreateTrueColor($x,$y);
ImageCopyResampled($dst,$src,0,0,0,0,$x,$y,$width,$height);
header('Content-Type: image/png');
ImagePNG($dst);
?>

12. Write a program to create PDF document in php.


<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP World!',1,1,'C');
$pdf->Output();
?>
Output :

13. Describe Implode and Explode function.


Imploding and Exploding are couple of important functions of PHP that can be
applied on strings or arrays.
The implode( ) function implodes an array into a string, and the explode function
explodes a string into an array.
That’s useful if you have stored your data in strings in files and want to convert those
strings into array elements
when your web application forms.
Implode()
The implode() is a built-in function in PHP and is used to join the elements of an
array.
The implode() function returns a string from the elements of an array.
If we have an array of elements, we can use the implode() function to join them all
to form one string. We basically
join array elements with a string. Just like join() function , implode() function also
returns a string formed from the
elements of an array.
Syntax :
string implode(separator, array);
The implode() function accepts two parameter out of which one is optional and one
is mandatory.
Separator : This is an optional parameter and is of string type. The values of the
array will be join to form a string and
will be separated by the separator parameter provided here. This is optional, if not
provided the default is “” (i.e. an
empty string).
Array : The array whose value is to be joined to form a string.
Example :
<?php
// PHP Code to implement join function
$InputArray = array('CO','IF','EJ');
// Join without separator
print_r(implode($InputArray));
print_r("<BR>");
// Join with separator
print_r(implode("-",$InputArray));
?>
Output :
COIFEJ
CO-IF-EJ

Explode()
The explode() function breaks a string into an array.
The explode() is a built in function in PHP used to split a string in different strings.
The explode() function splits a string based on a string delimeter, i.e. it splits the
string wherever the delimeter
character occurs. This function returns an array containing the strings formed by
splitting the original string.
Syntax :
array explode(separator, OriginalString, NoOfElements);
The explode( )function accepts three parameters of which two are compulsory and
one is optional. All the three
parameters are described as follows :
1. separator : This character specifies the critical points or points at which the string
will split, i.e. whenever this
character is found in the string it symbolizes end of one element of the array and start
of another.
2. OriginalString : The input string which is to be split in array.
3. NoOfElements : This is optional. It is used to specify the number of elements of the
array. This parameter can be any
integer ( positive , negative or zero)
(i) Positive (N) : When this parameter is passed with a positive value it means that the
array will contain this
number of elements. If the number of elements after separating with respect to the
separator emerges to be
greater than this value the first N-1 elements remain the same and the last element is
the whole remaining
string.
(ii) Negative (N) : If negative value is passed as parameter then the last N element of
the array will be trimmed
out and the remaining part of the array shall be returned as a single array.
(iii) Zero : If this parameter is Zero then the array returned will have only one element
i.e. the whole string.
When this parameter is not provided the array returned contains the total number of
element formed after
separating the string with the separator.
Example :
<html>
<body>
Web Based Application Development using PHP (MSBTE) 2-14 Arrays, Functions
and Graphics
<?php
$str = "PHP: Welcome to the world of PHP";
print_r (explode(" ",$str));
?>
</body>
</html>
Output :
Array ( [0] => PHP: [1] => Welcome [2] => to [3] => the [4] => world [5] => of [6]
=> PHP )

14. Explain for each loop with example


for each loop: This loop works with arrays and is used to traverse
through values in an array. For each loop iteration, the value of the
current array element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element.
Example :
<?php
$arr=array("Apple","Banana","Orange");
foreach($arr as $fruit)
{
echo("$fruit");
}
?>

Chapter 03

1. List classes and objects in php with syntax.


A class is a template for objects, and an object is an instance of class.
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 goes inside the braces :
Syntax :
<? Php
classname_of_class
{
// code goes here...
}
?>
Once you defined a class, you can create objects based on the class. To create an
object, you use the new keyword,
followed by the name of the class that you want to base the object on. You can then
assign this object to a variable,
much like any other value.
Example :
<?php
class Car
{
// Nothing to see here; move along
}
$Maruti = new Car();
$Honda = new Car();
print_r( $Maruti ); // Displays “Car Object ( )”
print_r( $Honda ); // Displays “Car Object ( )”
?>
Output :
Car Object ( ) Car Object ( )
This code first defines the empty Car class as before and then creates two new
instances of the Car class that is, two
Car objects. It assigns one object to a variable called $Maruti and another to a variable
called $Honda.
2. Explain constructors and destructors in PHP with example.
A constructor and a destructor are special functions which are automatically called
when an object is created and
destroyed.
Constructors are special member functions for initialize variables on the newly
created object instances from a class.
When creating a new object, it’s useful to set up certain aspects of the object at the
same time. For example, you
might want to set some properties to initial values, fetch some information from a
database to populate the object,
or register the object in some way.
Similarly, when it’s time for an object to disappear, it can be useful to tidy up
aspects of the object, such as closing
any related open files and database connections, or unsetting other related objects.
An object’s constructor method is called just after the object is created, and its
destructor method is called just before
the object is freed from memory.
constructor-
class MyClass
{
function __construct()
{
echo “Welcome to PHP constructor. <br / > ”;
}
}
$obj = new MyClass; // Displays “Welcome to PHP constructor.”

Destructors
<?php
class MyDestClass
{
function __construct()
{
print "In constructor<br>";
}
function __destruct()
{
print "Destroying " . __CLASS__ . "<br>";
}
}
$obj = new MyDestClass();//object is not created
?>
3. Write a PHP script Create a class as “Rectangle” with two properties as length
and width. Calculate area of rectangle for 2 objects.
<?php
class Rectangle
{
// Declare properties
public $length = 0;
public $width = 0;
// Method to get the area
public function getArea()
{
return ($this->length * $this->width);
}
}
// Create multiple objects from the Rectangle class
$obj1 = new Rectangle;
$obj2 = new Rectangle;
// Call the methods of both the objects
echo "Area of Object1:" . $obj1->getArea() . "<br>"; // Output: 0
echo "Area of Object2:" .$obj2->getArea(). "<br>"; // Output: 0
// Set $obj1 properties values
$obj1->length = 30;
$obj1->width = 20;
// Set $obj2 properties values
$obj2->length = 35;
$obj2->width = 50;
// Call the methods of both the objects again
echo "After calling”;
echo "Area of Object1:" .$obj1->getArea() . "<br>"; // Output: 600
echo "Area of Object2:" .$obj2->getArea() . "<br>"; // Output: 1750
?>
Output :
Area of Object1:0
Area of Object2:0
Area of Object1:600
Area of Object2:1750

4. Explain visibility modes in php.


The important concept of classes known as visibility. Each property of a class in PHP
can have one of three visibility
levels, known as public, private and protected :
o Public properties can be accessed by any code, whether that code is inside or
outside the class. If a property is
declared public, its value can be read or changed from anywhere in your script.
o Private properties of a class can be accessed only by code inside the class. So if
you create a property that’s
declared private, only methods inside the same class can access its contents.(If you
attempt to access the
property outside the class, PHP generates a fatal error.)
o Protected class properties are a bit like private properties in that they can’t be
accessed by code outside the
class, but there’s one subtle difference: any class that inherits from the class can also
access the properties.

You might also like