PHP unit1
Q) What is
a Variable? What are the rules to declare a variable in PHP?
Variable: A variable is a special
container that can “holds” a value, such as a number, string, object, array, or
a Boolean. Variables are fundamental to programming.
Rules to declare a Variable:
1.
A variable consists of a name, preceded by
a dollar sign ($).
2.
Variable names can include letters,
numbers, and the underscore character ( _ ), but they cannot include spaces.
3.
Names must begin with a letter or an
underscore.
4.
A semicolon (;) is used to end the
declaration of variable statement.
5.
When we declare a variable, we usually
assign a value to it in the same statement.
Examples:
$a;
$a_longish_variable_name;
$2453;
$sleepyZZZZ;
$num1
= 8;
$num2
= 23;
Q) Explain
Global Variable and Superglobal Variable.
Global Variables: In general, the assigned value of a variable is present only
within the function or script where it resides.
For
example, if you have scriptA.php that holds a variable called $name with a
value of shaik, and you want to
create scriptB.php that also uses a $name variable, you can assign to that
second $name variable a value of basha
without affecting the variable in scriptA.php. The value of the $name variable
is local to each script, and the assigned values are independent of each other.
However,
you can also define the $name variable as global within a script or function.
If the
$name variable is defined as a global variable in both scriptA.php and
scriptB.php, and these scripts are connected to each other (that is, one script
calls the other or includes the other), there will be just one value for the
now-shared $name variable.
Superglobal Variables: In addition
to global variables of your own creation, PHP has several predefined variables
called superglobals. These variables are always present, and their values are
available to all your scripts. Each of the following superglobals is actually
an array of other variables:
·
$_GET contains any variables provided to a
script through the GET method.
·
$_POST contains any variables provided to a
script through the POST method.
·
$_COOKIE contains any variables provided to
a script through a cookie.
·
$_FILES contains any variables provided to
a script through file uploads.
·
$_SERVER contains information such as headers,
file paths, and script locations.
·
$_ENV contains any variables provided to a
script as part of the server environment.
·
$_REQUEST contains any variables provided
to a script via GET, POST, or
COOKIE input mechanisms.
·
$_SESSION contains any variables that are
currently registered in a session.
Q) What are the different data types available in PHP script?
PHP is
loosely typed, meaning that it automatically determines the data type at the
time data is assigned to each variable.
Table
shows the eight standard data types available in PHP.
Example:
<?php
$testing;
// declare without assigning
echo “is
null? “.is_null($testing); // checks if null
echo
“<br/>”;
$testing
= 5;
echo “is
an integer? “.is_int($testing); // checks if integer
echo
“<br/>”;
$testing
= “five”;
echo “is
a string? “.is_string($testing); // checks if string
echo
“<br/>”;
$testing
= 5.024;
echo “is
a double? “.is_double($testing); // checks if double
echo
“<br/>”;
$testing
= true;
echo “is
boolean? “.is_bool($testing); // checks if boolean
echo
“<br/>”;
?>
Q) Write a note on Changing Type with settype( )
PHP use
the function settype( ), to change the type of a variable. To use settype( ), we
can place the variable to change and the type to change it to between the
parentheses and separate the elements with a comma, like this:
settype($variabletochange, ‘new type’);
Example:
<?php
$undecided
= 3.14;
echo “is
“.$undecided.” a double? “.is_double($undecided).”<br/>”; // double
settype($undecided,
‘string’);
echo “is
“.$undecided.” a string? “.is_string($undecided).”<br/>”; // string
settype($undecided,
‘integer’);
echo “is
“.$undecided.” an integer? “.is_integer($undecided).”<br/>”; //integer
settype($undecided,
‘double’);
echo “is
“.$undecided.” a double? “.is_double($undecided).”<br/>”; // double
settype($undecided,
‘bool’);
echo “is
“.$undecided.” a boolean? “.is_bool($undecided).”<br/>”; // boolean
?>
Q) Explain Operator and Expression.
Operator: An operator is a symbol or
series of symbols that, when used in conjunction with values, performs an
action, and usually produces a new value.
Operand: An operand is a value used in conjunction
with an operator. There are usually two or more operands to one operator.
Example:
(4 + 5)
Expression:
The
combination of operands with an operator to produce a result is called an expression.
An
expression is any combination of functions, values, and operators that resolves
to a value.
Example:
$user=(4 + 5)
Q) Explain different types of operators available in PHP.
1.
The Assignment Operator: The assignment
operator consists of the single character: =. The assignment operator takes the
value of the right-side operand and assigns it to the left-side operand.
Example: $name = “Shaik”;
2.
Arithmetic Operators: The arithmetic operators perform arithmetic operations.
Example:
3.
The Concatenation Operator: The
concatenation operator is represented by a single period (.). Treating both operands
as strings, this operator appends the right-side operand to the left-side operand.
Example: “hello”.” world” returns “hello world”
4.
Combined Assignment Operators: A
combined assignment operator consists of a standard operator symbol followed by
an equal sign.
Example: $x = 4;
$x = $x + 4;
// $x now equals 8
5.
Automatically Incrementing and Decrementing an Integer Variable: PHP provides some special operators that allow you to add or
subtract the integer constant 1 from an integer variable, assigning the result
to the variable itself. These are known as the post-increment and post-decrement
operators.
Example $x++; // $x is
incremented by 1
$x--; // $x is
decremented by 1
If you
use the post-increment or post-decrement operators in conjunction with a
conditional operator, the operand is modified only after the first operation
has finished:
$x = 3;
$y = $x++ + 3;
In this
instance, $y first becomes 6 (the result of 3 + 3), and then $x is incremented.
PHP also
provides the pre-increment and pre-decrement operators. These
operators behave in the same way as the post-increment and post-decrement
operators, but they are written with the plus or minus symbols preceding the
variable:
EXAMPLE:
++$x; // $x is incremented by 1
--$x; // $x is decremented by 1
6.
Comparison Operators: Comparison
operators perform comparative tests using their operands and return the Boolean
value true if the test is successful or false if the test fails
The ==
operator tests equivalence, whereas the = operator assigns value. Also,
remember that === tests equivalence with regard to both value and type.
7.
Logical Operators: Logical operators test combinations of Boolean values.
Example:
8.
Operator Precedence: When you use an operator within an expression, the PHP engine
usually reads your expression from left to right.
The
following is a list of the operators covered in this chapter in precedence
order (those with the highest precedence listed first):
1.
++, --, (cast)
2.
/, *, %
3.
+, -
4.
<, <=, =>, >
5.
==, ===, !=
6.
&&
7.
||
8.
=, +=, -=, /=, *=, %=, .=
9.
and
10.
xor
11.
or
Q) Explain the concept of Constants in PHP.
PHP use builtin
define( ) function to create a constant, which subsequently cannot be changed unless
you specifically define( ) it again. To use the define( ) function, place the name
of the constant and the value you want to give it within parentheses and
separated by a comma.
define(“YOUR_CONSTANT_NAME”, 42);
The
value you want to set can be a number, a string, or a Boolean. By convention, the
name of the constant should be in capital letters. Constants are accessed with the
constant name only; no dollar symbol is required.
Example:
<?php
define(“THE_YEAR”, “2012”);
echo “It is the year “.THE_YEAR;
?>
Constants
can be used anywhere in your scripts, including in functions stored in external
files.
Q) Write a note on Pre-Defined Constant.
PHP
provides a large number of predefined constants to any script which it runs. There are nine magical
constants that change depending on where they are used. These special constants
are case-insensitive and are as follows:
|
A few "magical" PHP constants
|
|
|
Name
|
Description
|
|
__LINE__
|
The current line number of the file.
|
|
__FILE__
|
The full path and filename of the file with symlinks resolved.
If used inside an include, the name of the included file is returned.
|
|
__DIR__
|
The directory of the file. If used inside an include, the
directory of the included file is returned. This is equivalent
to dirname(__FILE__). This directory name does not have a trailing slash
unless it is the root directory.
|
|
__FUNCTION__
|
The function name.
|
|
__CLASS__
|
The class name. The class name includes the namespace it was
declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also
in traits. When used in a trait method, __CLASS__ is the name of the class
the trait is used in.
|
|
__TRAIT__
|
The trait name. The trait name includes the namespace it was
declared in (e.g. Foo\Bar).
|
|
__METHOD__
|
The class method name.
|
|
__NAMESPACE__
|
The name of the current namespace.
|
Flow Control Functions in PHP
Q) Explain briefly about flow control functions in PHP.
1. The if Statement: The if statement evaluates an expression found
between parentheses. If this expression results in a true value, the statement is executed.
Otherwise, the statement is skipped entirely.
Syntax:
if (expression)
{
// code to execute if the expression
evaluates to true
}
Example:
<?php
$mood = “happy”;
if ($mood == “happy”) {
echo “Shaik! I’m in a good
mood!”;
}
?>
2. else Clause with
the if Statement: When working with an if statement, you might want to define an
alternative block of code that should be executed if the expression you are
testing evaluates to false. You can do
this by adding else to the if statement followed by a further block of
code:
if (expression) {
// code to execute if the expression evaluates to true
} else {
// code to execute in all other cases
}
<?php
$mood = “sad”;
if ($mood == “happy”) {
echo “Shaik! I’m in a good
mood!”;
} else {
echo “I’m in a $mood
mood.”;
}
?>
3. Using the elseif
Clause with the if Statement: You can use
an if...elseif...else clause to test multiple expressions
if (expression) {
// code to execute if the expression evaluates to true
} elseif (another expression) {
// code to execute if the previous expression failed
// and this one evaluates to true
} else {
// code to execute in all other cases
}
<?php
$mood = “sad”;
if ($mood == “happy”) {
echo “Hooray! I’m in a good
mood!”;
} elseif ($mood == “sad”) {
echo “Awww. Don’t be
down!”;
} else {
echo “I’m neither happy nor
sad, but $mood.”;
}
?>
4. The switch
Statement: The switch statement is
an alternative way of changing flow, based on the evaluation of an expression.
A switch statement
evaluates only one expression in a list of expressions, selecting the correct
one based on a specific bit of matching code.
switch (expression) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
EXAMPLE:
<?php
$mood = “sad”;
switch ($mood) {
case “happy”:
echo “Hooray! I’m in a good mood!”;
break;
case “sad”:
echo “Awww. Don’t be down!”;
break;
default:
echo “I’m neither happy nor sad, but $mood.”;
break;
}
?>
5. Using the ?: Operator:
The ?: or ternary
operator is similar to the if statement, except that it returns a value
derived from one of two expressions separated by a colon.
This construct provides you with three parts of the whole, hence
the name ternary. The expression used to generate the returned value depends on
the result of a test expression:
(expression) ? returned_if_expression_is_true : returned_if_expression_is_false;
EXAMPLE
<?php
$mood =
“sad”;
$text =
($mood == “happy”) ? “I am in a good mood!” : “I am in a $mood
mood.”;
echo
“$text”;
?>
Loop statements are
specifically designed to enable you to perform repetitive tasks because they
continue to operate until a specified condition is achieved or until you
explicitly choose to exit the loop.
The while Statement
The while statement looks similar in structure to a
basic if statement,
but has the ability to loop:
while (expression) {
// do
something
}
Unlike
an if statement, a while statement executes for as long as the
expression evaluates to true, over and
over again if need be. Each execution of a code block within a loop is called
an iteration. Within the block, you usually change something that affects
the while statement’s
expression; otherwise, your loop continues indefinitely.
<?php
$counter
= 1;
while
($counter <= 12) {
echo
$counter.” times 2 is “.($counter * 2).”<br />”;
$counter++;
}
?>
The do...while Statement
A do...while statement looks a little like a while statement turned on its head.
The
essential difference between the two is that the code block is executed before the truth
test and not after it:
do {
// code
to be executed
} while (expression
<?php
$num =
1;
do {
echo
“The number is: “.$num.”<br />”;
$num++;
} while
(($num > 200) && ($num < 400));
?>
The for Statement
Anything
you want to do with a for statement can
also be done with a while statement,
but a for statement is
often a more efficient method of achieving the same
effect.
In Listing 6.6, you saw how a variable was initialized outside the while statement and then tested within its
expression and incremented within the code block.
With a
for statement, you can achieve this same series
of events, but in a single line of code. This allows for more compact code and
makes it less likely that you might forget to increment a counter variable,
thereby creating an infinite loop:
for (initialization expression; test expression; modification expression) {
// code
to be executed
}
<?php
for
($counter=1; $counter<=12; $counter++) {
echo
$counter.” times 2 is “.($counter * 2).”<br />”;
}
?>
Breaking Out of Loops with the break Statement
Both while and for statements incorporate a built-in test expression with which you
can end a loop. However, the break statement enables you to break out of a loop based on the
results of additional tests. This can provide a safeguard against error.
Listing 6.9 creates a simple for statement that divides a large number by a variable that is
incremented, printing the result to the screen.
<?php
for ($counter=1; $counter <= 10;
$counter++) {
$temp =
4000/$counter;
echo
“4000 divided by “.$counter.” is...”.$temp.”<br />”;
}
?>
Nesting Loops
Loops
can contain other loop statements, as long as the logic is valid and the loops
are tidy. The combination of such statements proves particularly useful when
working with dynamically created HTML tables.
<?php
echo
“<table style=\”border: 1px solid #000;\”> \n”;
for
($y=1; $y<=12; $y++) {
echo
“<tr> \n”;
for
($x=1; $x<=12; $x++) {
echo
“<td style=\”border: 1px solid #000; width: 25px;
text-align:center;\”>”;
echo ($x
* $y);
echo
“</td> \n”;
}
echo
“</tr> \n”;
}
echo
“</table>”;
?>
What Is a Function?
A function is a
self-contained block of code that can be called by your scripts. When called,
the function’s code is executed and performs a particular task. You can pass
values to a function, which then uses the values appropriately—storing them,
transforming them, displaying them, whatever the function is told to do. When
finished, a function can also pass a value back to the original code that
called it into action.
Calling Functions
Functions
come in two flavors: those built in to the language and those you define
yourself. PHP has hundreds of built-in functions. Look at the following snippet
for an
example
of a function in use:
strtoupper(“Hello
Web!”);
This
example calls the strtoupper() function,
passing it the string “Hello Web!”.
The
function then goes about its business of changing the contents of the string to
uppercase
letters. A function call consists of the function name (strtoupper in this
case)
followed by parentheses. If you want to pass information to the function, you
place
it between these parentheses. A piece of information passed to a function in
this
way is called an argument. Some functions require that more than one argument
be
passed to them, separated by commas:
some_function($an_argument, $another_argument);
<?php
$num = -321;
$newnum
= abs($num);
echo
$newnum;
//prints “321”
?>
This
example assigns the value -321 to a variable $num. It then passes that variable to the abs() function, which makes the necessary
calculation and returns a new value. The code assigns this to the variable $newnum and displays the result.
Put
these lines into a text file called abs.php and place this file in your web server document root. When you access
this script through your web browser, it produces the following:
321
In
fact, Listing 7.1 could have dispensed with temporary variables altogether,
passing the number straight to the abs() function and directly printing the result:
echo abs(-321);
Defining a Function
You
can define your own functions using the function statement:
function
some_function($argument1, $argument2)
{
//function
code here
}
The
name of the function follows the function statement and precedes a set of parentheses. If your function
requires arguments, you must place comma-separated variable names within the
parentheses. These variables are filled by the values passed to your function.
Even if your function doesn’t require arguments, you must nevertheless supply
the parentheses.
<?php
function bighello()
{
echo
“<h1>HELLO!</h1>”;
}
bighello();
?>
Returning Values from User-Defined Functions
The
previous example output an amended string to the browser within the
printBR()
function. Sometimes, however, you will want a function to
provide a
value
that you can work with yourself. If your function has transformed a string that
you have provided, you might want to get the amended string back so that you
can pass it to other functions. A function can return a value using the return statement in conjunction with a value. The return statement stops the execution of the
function and sends the value back to the calling code.
<?php
function
addNums($firstnum, $secondnum)
{
$result
= $firstnum + $secondnum;
return
$result;
}
echo addNums(3,5);
//will
print “8”
?>
It can
be the result of an expression:
return
$a/$b;
It can
be the value returned by yet another function call:
return
another_function($an_argument);
Variable Scope
A
variable declared within a function remains local to that function. In other
words, it is not available outside the function or within other functions. In
larger projects, this can save you from accidentally overwriting the contents
of a variable when you declare two variables with the same name in separate
functions
<?php
function
test()
{
$testvariable
= “this is a test variable”;
}
echo
“test variable: “.$testvariable.”<br/>”;
?>
Accessing Variables with the global Statement
From
within one function, you cannot (by default) access a variable defined
in another function or elsewhere in the script. Within a function, if you
attempt to use a variable with the same name, you will only set or access a
local variable.
<?php
$life =
42;
function
meaningOfLife()
{
echo
“The meaning of life is “.$life”;
}
meaningOfLife();
?>
Saving State Between Function Calls with the static
Statement
Local
variables within functions have a short but happy life—they come into being
when
the function is called and die when execution is finished, as they should.
Occasionally, however,
you might want to give a function a rudimentary memory.
Assume
that you want a function to keep track of the number of times it has been
called so that numbered
headings can be created by a script
<?php
$num_of_calls
= 0;
function
numberedHeading($txt)
{
global
$num_of_calls;
$num_of_calls++;
echo
“<h1>”.$num_of_calls.” “.$txt.”</h1>”;
}
numberedHeading(“Widgets”);
echo
“<p>We build a fine range of widgets.</p>”;
numberedHeading(“Doodads”);
echo “<p>Finest in the
world.</p>”;
?>
More About Arguments
You’ve
already seen how to pass arguments to functions, but there’s plenty more to
cover. This section covers a technique for giving your arguments default values
and explores a method of passing variables by reference rather than by value.
This means that the function is given an alias of the original value rather
than a copy of it.
Setting Default Values for Arguments
PHP
provides a nifty feature to help build flexible functions. Until now, you’ve
heard that some functions require one or more arguments. By making some
arguments optional, you can render your functions a little less autocratic.
<?php
function
fontWrap($txt, $fontsize)
{
echo
“<span style=\”font-size:$fontsize\”>”.$txt.”</span>”;
}
fontWrap(“A
Heading<br/>”,”24pt”);
fontWrap(“some
body text<br/>”,”16pt”);
fontWrap(“smaller
body text<br/>”,”12pt”);
fontWrap(“even
smaller body text<br/>”,”10pt”);
?>
Passing Variable References to Functions
When
you pass arguments to functions, they are stored as copies in parameter
variables. Any changes made to these variables in the body of the function are
local to that function and are not reflected beyond it, as illustrated in
Listing
<?php
function
addFive($num)
{
$num
+= 5;
}
$orignum
= 10;
addFive($orignum);
echo
$orignum;
?>
Testing for the Existence of a Function
You do
not always know that a function exists before you try to invoke it. Different
builds
of the PHP engine might include different functionality, and if you are writing
a script that may be run on multiple servers, you might want to verify that key
features are available. For instance, you might want to write code that uses
MySQL if MySQL-related functions are available but simply log data to a text
file otherwise.
You
can use function_exists() to check for the availability of a function.
function_
exists()
requires a string representing a function name. It returns true if the
function
can be located, and false otherwise.
<?php
function
tagWrap($tag, $txt, $func = “”)
{
if ((!empty($txt)) &&
(function_exists($func))) {
$txt =
$func($txt);
return
“<”.$tag.”>”.$txt.”</”.$tag.”><br/>”;
} else
{
return
“<strong>”.$txt.”</strong><br/>”;
}
}
function
underline($txt)
{
return
“<span style=\”text-decoration:underline;\”>”.$txt.”</span>”;
}
echo
tagWrap(‘strong’, ‘make me bold’);
echo
tagWrap(‘em’, ‘underline and italicize me’, “underline”);
echo
tagWrap(‘em’, ‘make me italic and quote me’,
create_function(‘$txt’,
‘return “"$txt"”;’));
?>
Comments
Post a Comment