0% found this document useful (0 votes)
97 views10 pages

Chapter 1.1-1.2

php

Uploaded by

34Shreya Chauhan
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)
97 views10 pages

Chapter 1.1-1.2

php

Uploaded by

34Shreya Chauhan
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/ 10

Chapter 1

Expressions and control statements in PHP

1.1. History and Advantages of PHP, Syntax of PHP


History of PHP: The initial version of PHP was introduced by Rasmus Lerdorf in 1994.
Evolution of PHP:
1. PHP 1.0 announcement was posted to the Usenet newsgroup in June 1995. It was concerned with
password protecting pages, easily creating forms, and accessing form data on subsequent pages. The
business logic for these features was written in C. Apache API made it easier to add functionality like
PHP to the server.
2. PHP 2.0 announcement was done in April 1996. IT introduced first time the term ‘scripting language.
PHP 1’s simplistic tag-replacement code was replaced with a parser that could handle a more
sophisticated embedded tag language. It was concerned with web pages for creating conditional HTML,
custom tags, and other features.
3. PHP 3.0 announcement was done in June 1998. In this version, Zeev Suraski and Andi Gutmans from
Israel, were involved in rewriting the parsing engine. Changes in this version included abstracting the
layer between the language and the web server, adding a thread safety mechanism and adding a more
advanced, two stage parse/execute tag-parsing system.
PHP is a simple, yet powerful language designed for creating HTML content. It is a server scripting
language and used for making dynamic and interactive web pages.
PHP can be used in three primary ways:
1. Server-side scripting: It was originally designed to create dynamic web content. to generate HTML,
programmer need the PHP parser and a web server through which coded documents are sent. PHP is also
used for generating XML documents, graphics, flash animations, pdf files, etc.
2. Command line scripting: PHP can run scripts from the command line just like Perl or Unix shell. It is
involved in command line scripts for system administration tasks, such as backup and log parsing.
3. Client-side GUI application: With this programmer can write full-blown, cross platform GUI
applications.
Advantages of PHP:
Speed up custom web application development : PHP programmers have to write web applications based
on complex business requirements. For this they have to explore ways to make the web application deliver
richer user experience. The tools, features, and code snippets provided by PHP frameworks help developers
to speed up custom web application development.

Simplify web application maintenance : PHP does not emphasize on code readability and maintainability.
The PHP frameworks simplify web application development and maintenance by supporting model-view-
controller (MVC) architecture. The developers can take advantage of MVC architecture to divide a web
application into models, views and controllers. They can use a MVC framework for PHP to keep the
application’s user interface and business logic layers separated.

No need to write additional code : PHP does not allow programmers to express concepts without writing
longer lines of code. Hence, the PHP programmers have to write lengthy and complex code while adding
features or functionality to a website. The PHP frameworks reduce coding time significantly by providing
code generation feature. The code generation features provided by certain PHP frameworks enable
programmers to keep the source code of web application clean and maintainable.
Work with databases more efficiently : Most PHP frameworks allow programmers to work with a number
of widely used relational databases. Some frameworks further simplify database operations by providing
object relational mapping (ORM) systems. The programmers can take advantage of the ORM systems to
perform database operations without writing lengthy SQL code. The ORMs even allows programmers to
write object code directly in PHP programming language.

Automate common web development tasks : While building a web application, developers have to perform
a number of tasks in addition to writing code. Some of these common web development tasks require
programmers to invest additional time and effort. The functions and tools provided by PHP frameworks help
developers to automate common web development tasks like caching, session management, authentication,
and URL mapping.

Protect websites from targeted security attacks : PHP is considered to be one of the most unsecured
programming languages. Often programmers have to explore ways to protect the PHP applications from
various security attacks. The built-in security features and mechanisms provided by PHP framework make it
easier for developers to protect the website from existing and emerging security threats. Also, the PHP web
developers can easily prevent common security threats like SQL injections, cross-site request forgery, and
data tampering.

Perform unit testing efficiently : While building a custom web application, developers have to perform unit
testing regularly to evaluate its individual units or components. A large percentage of web developers use
PHPUnit to perform unit tests quickly and efficiently. In addition to being an object-oriented unit testing
framework for PHP, PHPUnit further helps developers to write and run unit tests by providing coding
assistance. Many PHP frameworks support PHPUnit natively, and enable programmers to perform unit
testing smoothly.

No need to increase web development cost : As an open source server-side programming language, PHP
helps users to curtail web development cost significantly. The developers also have option to choose from
several open source web frameworks for PHP. They can even avail the features and tools provided by these
open source PHP frameworks speed up custom web application development without increasing project
overheads.

Disadvantages of Using PHP Frameworks

Programmers need to learn PHP frameworks instead of PHP : The PHP frameworks enable programmers
to add functionality to a web application without writing additional code. But the programmers have to put
some time and effort to learn the PHP framework. They can even learn and use certain frameworks without
being proficient in PHP coding.

Quality of PHP frameworks differs : Most widely used PHP frameworks are open source and free. Hence,
the web developers can take advantage of these web frameworks without increasing the project cost. But the
community strength of individual frameworks differs. Hence, some PHP frameworks lack prompt and
adequate support.

Lack of option to modify core behavior : In addition to proving a basic structure for web application
development, the PHP frameworks further accelerate custom web application development. But the
developers still lack any option to make changes to the core behavior of these frameworks. Some frameworks
even requirements developers to use specific tools or adopt a particular web development pattern.

Affect Speed and performance of websites : Most PHP frameworks come with robust features and tools to
accelerate development of large and complex websites. But web developers may not need these advanced
features while building small or simple web applications. Also, these additional features often impact the
performance and speed of websites adversely.
Syntax of PHP :
PHP pages are generally HTML pages with PHP commands embedded in them.
PHP code is placed between <? … ?> tags.

Case Sensitivity : The names of user-defined classes and functions, as well as built-in constructs and
keywords such as echo, while, class, etc., are case-insensitive.
Example: Below these three lines are equivalent
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");
Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different
variables.

Statements and Semicolons :


A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or
as complicated as a loop with multiple exit points.
Example:
1. echo "Hello, world";
2. $a = 1;
3. if ($a == $b)

PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a
block of code, such as a conditional test or loop, does not need a semicolon after a closing brace.
Example:
if ($needed)
{
echo "We must have it!"; // semicolon required here
} // no semicolon required here after the brace

The semicolon, however, is optional before a closing PHP tag:


Example:
<?php
if ($a == $b)
{
echo "Rhyme? And Reason?";
}
echo "Hello, world" // no semicolon required before closing tag
?>

Whitespace and Line Breaks :


In general, whitespace doesn’t matter in a PHP program. One can spread a statement across any number of
lines, or lump a bunch of statements together on a single line.
Example:
raisePrices($inventory, $inflation, $cost, $greed);
Above statement can be written as below with more whitespace:
raisePrices (
$inventory ,
$inflation ,
$cost ,
$greed
);
Comments :
Comments are used to add extra information about the code which is ignored by PHP at execution time. This
extra information is for helping others to understand the code.
PHP provides several ways to include comments within code, all of which are borrowed from existing
languages such as C, C++, and the Unix shell.
Shell-style comments : When PHP encounters a hash mark character (#) within the code, everything from
the hash mark to the end of the line or the end of the section of PHP code (whichever comes first) is
considered a comment.
Example: # calculate compounded interest
C++ comments : When PHP encounters two slashes (//) within the code, everything from the slashes to the
end of the line or the end of the section of code, whichever comes first, is considered a comment.
Example : // calculate compounded interest

C comments : (Multi line comment) While shell-style and C++-style comments are useful for annotating
code or making short notes, longer comments require a different style. PHP supports block comments. When
PHP encounters a slash followed by an asterisk (/*), everything after that, until it encounters an asterisk
followed by a slash (*/), is considered a comment.
Example:
/* In this section, we take a bunch of variables and
assign numbers to them. There is no real reason to
do this, we're just having fun.
*/

PHP echo statement: echo statement is used to display output on screen. It can be used with or without
parenthesis().
Syntax: echo “text to be displayed”; OR echo (expression);
Example: echo “welcome to PHP”;

Writing a first program in PHP :


Step 1: Script/code writing - Write script in notepad and save it with filename.php inside htdocs folder in
Xampp folder in C: .

Step 2: Open Xampp control panel and start Apache server.

Step 3: For execution, Open web browser and in address bar type http://localhost/filename.php and enter.

All PHP scripts are written in code blocks. These blocks can be embedded into HTML with <?php at the
start and ?> at the end. Everything outside these blocks will be ignored by the PHP interpreter and instead
passes to the web server to display it to the client.
Program : Script to print ‘Welcome to PHP’.
Script: Output:
<html>
<head>
<title> Welcome to PHP</title>
</head>
<body>
<?php echo "Welcome to PHP"?>
</body>
</html>

1.2 Variables,Data Types,Expression and operators,constants


Literals : A literal is a data value that appears directly in a program. Examples of literals in PHP are
2001,1.4142,"Hello World",'Hi',true,null

Identifiers : An identifier is simply a name. In PHP, identifiers are used to name variables, functions,
constants, and classes. The first character of an identifier must be an ASCII letter (uppercase or lowercase),
the underscore character (_), or any of the characters between ASCII 0x7F and ASCII 0xFF. After the initial
character, these characters and the digits 0–9 are valid.

Variables : A variable is a container that store data. In PHP, variable always starts with the dollar($)
symbol followed by any combination of characters, provided that the first character following the $ symbol
is a valid letter or underscore.

Rules for PHP variables:


 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 cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different variables)

Syntax : $variable_name=’value’;
Example : $no=5;
$no=12.5;
$name=’abc’; // use single quote

Keywords : A keyword is a reserved word with predefined meaning for the language’s core functionality.
One cannot give a variable, function, class, or constant the same name as a keyword. Keywords in PHP are
case-insensitive.
__CLASS__ abstract endfor interface require declare
__DIR__ and endforeach isset() require_once default
__FILE__ array() endif list() return die()
__FUNCTION__ as endswitch namespace callable do
__LINE__ break endwhile new case for
__METHOD__ echo eval() or catch foreach
__NAMESPACE__ else exit() print class function
__TRAIT__ elseif extends private clone global
__halt_compiler() empty() final protected const goto
enddeclare insteadof public continue if
include_once switch try var implements
instanceof throw unset() while include
static trait use xor
Data Types :
PHP provides eight types of values, or data types:
Four are scalar (single-value) types: integers, floating-point numbers, strings, and Booleans.
Two are compound (collection) types: arrays and objects.
Two are special types: resource and NULL.

Integers : Integers are whole numbers, such as 1, 12, and 256. Integer literals can be written in decimal,
octal, or hexadecimal.

Decimal values are represented by a sequence of digits, without leading zeros. The sequence may begin with
a plus (+) or minus (−) sign. If there is no sign, positive is assumed.
Examples of decimal integers include the following: 1998 , −641 , +33
Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers, octal
numbers can be prefixed with a plus or minus. Here are some example octal values and their equivalent
decimal values: 0755 // decimal 493 , +010 // decimal 8
Hexadecimal values begin with 0x, followed by a sequence of digits (0–9) or letters (A–F). The letters can
be upper- or lowercase but are usually written in capitals. Like decimal and octal values, you can include a
sign in hexadecimal numbers: 0xFF // decimal 255 , 0x10 // decimal 16 , -0xDAD1 // decimal −56017
Binary numbers begin with 0b, followed by a sequence of digits (0 and 1). Like other values, you can
include a sign in binary numbers: 0b01100000 // decimal 1 , 0b00000010 // decimal 2

Floating-Point Numbers :Floating-point numbers (often referred to as real numbers) represent numeric
values with decimal digits. This allows numbers between 1.7E−308 and 1.7E+308 with 15 digits of accuracy.
PHP recognizes floating-point numbers written in two different formats.
General format : 3.14 , 0.017 , -7.1
Scientific format: 0.314E1 // 0.314*10^1, or 3.14 , 17.0E-3 // 17.0*10^(-3), or 0.017
Floating-point values are only approximate representations of numbers. For example, on many systems 3.5
is actually represented as 3.4999999999.

Strings : As strings are very common in web applications, PHP includes core-level support for creating
and manipulating strings. A string is a sequence of characters of arbitrary length. String literals are delimited
by either single or double quotes: 'big dog' or "fat hog" .
There are two types of strings:
1. Parsed string:- These type of strings are represented using double quotes are parsed by PHP. When a
string is defined using double quotes, any references to variables within that string will automatically be
replaced with their respective values.
Example: $no=10;
$str1=” My roll number is $no”
echo $str1;
The above statement displays output as ‘ My roll number is 10’. PHP read the string str1 and it take $no as a
reference to variable ‘no’ and replaces it with its value at the time of display.

2. Unparsed string: - These type of strings are represented using single quote and processed as it is.When a
string is defined using single quote, any reference to variables in that string does not replace with their
respective values. It displays it with variable name not the value.
Example: $no=10;
$str1=’ My roll number is $no’
echo $str1;
The above statement displays output as ‘ My roll number is $no’. PHP read the string str1 and it does not
take $no as a reference to variable ‘no’ and displays it as it is in the output.
Double quotes also support a variety of string escapes as shown in table below:
Escape sequence Character represented
\" Double quotes
\n Newline
\r Carriage return
\t Tab
\\ Backslash
\$ Dollar sign
\{ Left Brace
\} Right Brace
\[ Left bracket
\] Right bracket
\0 through \777 ASCII character represented by octal value
\x0 through \xFF ASCII character represented by hex value
PHP provides operators and functions to compare, disassemble, assemble, search, replace, and trim strings,
as well as a host of specialized string functions for working with HTTP, HTML, and SQL encoding.

Booleans : A Boolean value represents either true(1) or false(0). Boolean values are often used in
conditional testing.
Example: $var=TRUE;

Arrays : An array holds a group of values, which you can identify by position (a number, with zero being
the first position) or some identifying name (a string), called an associative index.
Example: The array() construct creates an array.
$person = array("Edison", "Wankel", "Crapper");
$creator = array('Light bulb' => "Edison", 'Rotary Engine' => "Wankel", 'Toilet' => "Crapper");

Objects : PHP also supports object-oriented programming (OOP). OOP promotes clean modular design,
simplifies debugging and maintenance, and assists with code reuse.
Classes are the building blocks of object-oriented design. A class is a definition of a structure that contains
properties (variables) and methods (functions). Classes are defined with the class keyword.
Example:
class Person
{
public $name = '';
function name ($newname = NULL)
{
if (!is_null($newname))
{ $this->name = $newname; }
return $this->name;
}
}
Once a class is defined, any number of objects can be made from it with the new keyword, and the object’s
properties and methods can be accessed with the -> construct:
$ed = new Person;
$ed->name('Edison');

Resource : Many modules provide several functions for dealing with the outside world. For example,
every database extension has at least a function to connect to the database, a function to send a query to the
database, and a function to close the connection to the database. Programmer can have multiple database
connections open at once, the connect function gives programmer something by which to identify that
unique connection when programmer call the query and close functions such as a resource (or a “handle”).
Each active resource has a unique identifier. Each identifier is a numerical index into an internal PHP lookup
table that holds information about all the active resources. PHP maintains information about each resource in
this table, including the number of references to the resource throughout the code. When the last reference to
a resource value goes away, the extension that created the resource is called to free any memory, close any
connection, etc., for that resource.
Example : $res = database_connect();
database_query($res);

NULL : The NULL value represents a variable that has no value.


Example:
$aleph = NULL;

Use the is_null() function to test whether a value is NULL—for instance, to see whether a variable has a
value: if (is_null($x))
{
// $x is NULL
}

Expressions and Operators :


An expression is a combination of operands and operators which can be evaluated to produce a value.
Operands can be values or variables. An operator reads the operands and perform operation on them.
Example: $c=$a+$b;

Types of operators:
Operator Type Operator
Arithmetic operators: Addition(+) , Subtraction(-) , Multiplication(*) , Division(/) ,
Modulus(%) , Increment($x++,++$x) , Decrement($x--,--$x)
Comparison operators: less than(<), less than or equal(<=), greater than(>),greater than or
equal(>=), equal to equal to(= =),Not equal to(!=)(< >),Type and value
equality(= = = ), Type and value inequality(!= =)
Assignment operators: assign(=),+=,-=,*=,/=,%=,.=,&=,|=,^=,~=,<<=,>>=
Logical operators: AND(&&),OR(||),NOT(!)
Bitwise operators: NOT(~),AND(&)(and),XOR(^)(xor),OR(|)(or),Bitwise shift left(<<),
Bitwise shift right(>>)
String concatenation : dot(.)
List operator : comma (,) : Separator
Casting operators : (int) , (float) , (bool), (string), (array),(object),(unset)
Array subscript : [ - used to define an array
Inhibit error/error suppression: @ - It is used to prevent error messages from being created by some
operators or functions.
Type testing : instanceof
Create new object: clone , new
String concatenate operator: dot (.) operator is used to concatenate strings. The concatenation operator
appends the righthand operand to the lefthand and returns the resulting string.
Example:
<?
$a=10;
$b='My rollnumber is ' . $a . ' in class IF5I';
echo $b;
?>
Output: My rollnumber is 10 in class IF5I

Casting operators (Explicit Casting) : These operators are used to convert a value of one data type into
another data type. To use casting operators, place the operator to the left of operand.
Example :
$a=”5”; //Variable a holds string value 5
$a= (int)$a; // (int) operator converts string into integer. Now a contains integer value 5

(int)- Converts value of variable into integer data type


(bool)- Converts value of variable into boolean data type
(float)- Converts value of variable into floating point data type
(string)- Converts value of variable into string data type
(array)- Converts value of variable into array data type
(object)- Converts value of variable into object data type
(unset)- It is used to destroy the specified variables. For example: unset($a)

Type operator :- Instanceof - It is used to test whether a variable is an instantiated object of a given class or
implements an interface.
Example:
$a=new classstud;
$r=$a instanceof classstud;
echo $r; // returns true

Operators to create new object:


Operator new : It is used ti create an object from a class.
Syntax: $object_name= new class_name( );
Example: $s1=new student( );

Operator clone: IT is used to create a copy of an object.


Syntax: $new_obj_name=clone $existing_obj_name;
Example: $s1=new student( ); // new object creation
$s2=clone $s1; // copy existing object into new object.

Implicit Casting : PHP’s variables can store integers, floating-point numbers, strings, and more. PHP
converts values from one type to another as necessary. The conversion of a value from one type to another is
called casting. This kind of implicit casting is called type juggling in PHP.

The rules for the type juggling done by arithmetic operators are as follows:
Type of first Type of second Conversion performed
operand operand
Integer Floating point The integer is converted to a floating-point number.
Example:
$a=10;
$b=20.5;
echo $a+$b;
Output: 30.5
Integer String The string is converted to a number; if the value after conversion is a
floating point number, the integer is converted to a floating-point
number.
Example 1: Example 2:
$a="10"; $a="10";
$b=20; $b=3;
echo $a+$b; echo $a/$b;
Output: 30 Output: 3.33
Floating point String The string is converted to a floating-point number.
Example:
$a=10.5;
$b="3";
echo $a+$b;
Output: 13.5

Some other operators have different expectations of their operands, and thus have different rules.
For example, the string concatenation operator converts both operands to strings before concatenating them:
.
3 2.74 // gives the string 32.74

Constants : A constant is an identifier for a simple value; only scalar values—Boolean, integer, double,
and string—can be constants. Once set, the value of a constant cannot change. Constants are referred to by
their identifiers and are set using the define() function.
Example : define('PUBLISHER', "O'Reilly & Associates");
echo PUBLISHER;

You might also like