Upload
nguyenthuan
View
216
Download
0
Embed Size (px)
Citation preview
PHP Programming Language Term PaperTyler Roberts
CSC 41511/4/14
I. History of PHP
PHP/FI:
PHP is a server-side scripting language designed for web development. It was created in
1994 by Rasmus Lerdorf and released to the public in June of 1995. The original versions of PHP
were written in the C programming language with the purpose of tracking the number of page
visits to web sites. Because of the source code being released to the public for improvement it
was later equipped with more feature and functionality including database capabilities and
other dynamic web functions.
After being updated, it resembled the PHP we know today more closely, although still
being relatively underdeveloped. It now included Perl-like variables and HTML embedded
syntax. The HTML syntax was very inconvenient for programmers at the time because it needed
to be typed into the HTML comments. This called for another rewriting of the source code. The
language was now designed to be very similar to C in structure which was helpful for
programmers that previously used C and Perl.
PHP received another complete code update in 1996. This version of PHP began to be
used more commonly by web developers. In 1997 and 1998 PHP had several thousand users
around the world, and was used in approximately 1% of the domains on the internet. This low
number could be attributed to the fact that it was still an awkward language to code in,
considering most of it was done in the comments of HTML code as seen in appendix 1.
PHP 3, 4, and 5:
PHP 3.0 is where PHP started to gain the bulk of its features. Because PHP/FI was lacking
in users and features, students from Tel Aviv, Andi Gutmans and Zeev Suraski, began doing
another code rewrite of PHP on their own in 1997. Gutmans, Suraski, and Rasmus started
working together to develop a new programming language. PHP/FI was now changed to just
PHP, or PHP: Hypertext Preprocessor.
PHP 3.0 had new features letting end users interact with an interface with multiple
databases, protocols, APIs, as well as object-oriented support. In 1998 the use of PHP began to
spread and was being used on 10% of web servers, up from 1% in the previous year. As soon as
PHP 3.0 was released, Gutmans and Suraski were already working on a rewrite of PHP to
increase the way the language handles larger applications. This gave birth to PHP 4.0 which was
released in 2000 and contained a bundle of new features in its update such as support for more
web servers, HTTP sessions, output buffering, and several new language constructs. Currently
PHP is on version 5.6 and roughly 82% of known websites use it for server side programming. It
has become the most commonly used language for most web development programming.
II. Overview of PHP Language Design, Syntax, and Semantics
A. Names, Bindings, and Scopes
Variable names in the PHP language are case sensitive and must be preceded by a ‘$’.
Valid variable names start with a letter or ‘_’ and are then followed by any number of
letters, numbers, or underscores.
PHP’s closest thing to bindings is a functionality called Late Static Binding. The purpose
of this binding is to create a keyword that references a class that was initially called at
runtime through static inheritance, hence the name. The code in appendix 2 shows a basic
example of this feature.
PHP variables generally have one scope that spans into all included and required files.
PHP contains the keyword “global” that lets the user access global versions of variables that
may have a variable of the same name in the function. The code in appendix 3 shows an
example of using the “global” keyword. Another important keyword when dealing with
scope is the “static” keyword. A static variable exists only in a local function’s scope, and it
doesn’t lose its value when execution leaves the scope. The code in appendix 4 shows an
example of using the static keyword.
B. Data Types
PHP supports eight different primitive data types, including four scalar types: boolean,
integer, float, and string. It also supports two compound types: array and object, and two
special types: resource and NULL.
It also contains two “pseudo-types” that include mixed and number types. A mixed
variable’s purpose is for parameters that may accept multiple types of variables. A number
variable’s purpose is for a parameter that can be either an integer or a float type.
C. Expressions and Assignment Statements
According to the PHP manual, “Expressions are the most important building stones of PHP.
In PHP, almost anything you write is an expression. The simplest yet most accurate way to
define an expression is ‘anything that has a value’ ” (php.net).
The easiest examples of using expressions are assigning values to variables. For example
“$count = 5” is assigning the value 5 to the variable $count. Values that have been assigned
to variables can be integer, float, string, or boolean values. Comparison expressions in PHP
are made up of the usual >, >=, ==, !=, <, <=, as well as === (equal to and same type) and !==
(not equal to or not same type). PHP also allows for combined operator-assignment
expressions such as $count++, ++$count. You can also use these combined expressions like
$count = $count + 3. When dealing with arrays, assigning a value to a named key is
performed by using the “=>” operator. The last major feature is assignment by reference
which allows the user to use a statement like “$var1 = &$var2;” to have var2 always be
assigned the value of var1.
D. Statement- Level Control Structures
Intro
This section will list all of PHP’s statement level control statements, briefly explain it (it
will be assumed that the reader has basic knowledge of the common control structures, so
extra explanation will not be given unless PHP has a specific part that varies from the norm),
then show a basic example of the syntax and how it works. Note: The use of “echo” hasn’t
been covered yet but will be used in many of these examples. This statement prints
whatever is following it on the screen.
If
PHP’s “if” statement is very similar to most “if” statements. It follows the same
true/false Boolean logic. Below is an example:
<?php
if ($a > $b)
echo "a is greater than b";
?>
Else
The “else” statement follows an “if” statement and handles the functionality of the
statement if it is false instead of true. Below is an example:
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
Elseif/else if
“Elseif” is another way to do “if” and “else” statements; it combines the functionality of
both into one. Below is an example:
<?php
if ($a > $b) {
echo "a is greater than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
This lets you check for multiple things without re-stating “if” statements.
While
The “while” loop is the most basic loop that PHP has. It executes the statement inside it
for as long as the expression contained inside of it is true. Below is an example:
<?php
$i = 1;
while ($i <= 10) {
echo $i++;
}
?>
Do-while
“Do-while” is almost the same as a “while” statement except the expression it contains
is checked at the end instead of the start. You start with having any assignment inside of
“do” brackets then follow up with the “while” statement that will check to see if the above
code needs to be run again. Below is an example:
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
For
“For” loops are much more complicated than the previously listed loops. PHP’s “for”
loops have a fairly standard syntax, seen below:
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
Foreach
“Foreach” is a loop structure used for iterating through an array or object. Below is an
example:
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
?>
Switch
“Switch” statements preform almost the same functionality as a series of “if”
statements. Below is an example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
“Switch” statements can also check for strings as well (0, 1, and 2 would just need to be
switched with characters.)
E. Subprograms
Subprograms in PHP are defined by using the “include” or “required” statements. These
statements let the programmer use parts from multiple .php files. When a file is included,
the code it contains inherits the variable scope of the line on which the include occurs.
Below is a simple example of the usage of “include” (“require” could be substituted in for
“include” and it would work the same way):
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
“Include” can also be placed inside a function; if so, it follows the scope as if it was
declared inside that function.
F. Abstract Data Types and Encapsulation Constructs
Abstract Data Types
Abstract data types can be used in PHP in the form of stacks and queues. To create a
stack in PHP the coder would need to use the code in appendix part 6. After creating the
stack it’s possible to create a new object and push string onto the stack with the push()
function:
<?php
$myBooks = new ReadingList();$myBooks->push('A Dream of Spring');
$myBooks->push('The Winds of Winter');
$myBooks->push('A Dance with Dragons');
$myBooks->push('A Feast for Crows');
$myBooks->push('A Storm of Swords');
$myBooks->push('A Clash of Kings');
$myBooks->push('A Game of Thrones');
?>
and delete items from the stack with the pop() function:
<?php
echo $myBooks->pop(); // outputs 'A Game of Thrones'echo $myBooks->pop(); // outputs 'A Clash of Kings'echo $myBooks->pop(); // outputs 'A Storm of Swords'
?>
Queues are simpler in that it’s possible to have a class extend SplQueue then use code like the following to add items to the queue using the enqueue() function:
<?php
class ReadingList extends SplQueue{
}
$myBooks = new ReadingList(); $myBooks->enqueue('A Game of Thrones');
$myBooks->enqueue('A Clash of Kings');
$myBooks->enqueue('A Storm of Swords');?>
then remove items from the queue using the dequeue() function:
<?php
echo $myBooks->dequeue() . "n"; // outputs 'A Game of Thrones'echo $myBooks->dequeue() . "n"; // outputs 'A Clash of Kings'
?>
Encapulation
Encapsulation in PHP is fairly straightforward. To wrap data in an object you need to do
the following:
<?php
class App { private static $_user;
public function User( ) { if( $this->_user == null ) { $this->_user = new User(); } return $this->_user; }
}
class User { private $_name;
public function __construct() { $this->_name = "Joseph Crawford Jr."; }
public function GetName() { return $this->_name; }}$app = new App();echo $app->User()->GetName();?>
This wraps the data inside an object to be used as a “user”.
G. Support for ObjectOriented Programming
PHP has support for oop programming. Usage of public, protected, and private methods can
be used with classes and objects.
-Public - The method is publicly available and can be accessed by all subclasses.
-Protected - the method/function/property is available to the parent class and all
inheriting-classes.
-Private - the method is private and only available to the parent class/base class.
H. Concurrency
PHP's concurrency model is the web request. If you want to run some code in parallel,
curl to localhost. If you wrap an appropriate library around this, it looks just like Erlang's
actors. You can use multi-threading in PHP with the “pthreads” API. “pthreads is an object
oriented API that enables multi-threading functionality in PHP. See appendix 7 for example
code on how it is used.
I. Exception Handling and Event Handling
PHP’s exception handling follows the common scheme used in most languages. The
exceptions can be thrown, caught, and can also be surrounded in a “try” statement. If an
exception is thrown, the code inside is not executed. “Finally” blocks can also be used, if
used code within the “finally” block will be executed after the” try” and “catch” blocks no
matter what. Appendix 5 has a list of the XML handlers PHP uses but usually no front-end
event handling occurs in PHP; this is usually done by a scripting language like JavaScript.
J. Other Issues of your Language
Although this is not an issue, this section is going to list and briefly explain some of the
important predefined variables used in PHP given that they were not covered in the paper
thus far.
$GLOBALS - References all variables always available in global scope.
$_GET - HTTP GET variables (used to get information from databases or other web
services).
$_POST- HTTP POST variables (used to post information to databases or other web
services.).
$_COOKIE -HTTP Cookies.
$argv - Array of arguments passed to the script.
III. Evaluation of PHP
A. Readability
If written correctly PHP is relatively easy to read. Almost all of the standard
programming language essentials have a very familiar syntax, so if the coder has basic
coding knowledge they would be able to read most PHP code without even doing any
research.
B. Writability
Basic PHP coding is extremely easy to write but once the coder gets into the more
complex back-end coding they will definitely need to research because the main purposes of
PHP are very specific. If the coder isn’t familiar with communicating with databases and
other web services they might get lost without guidance.
C. Reliability
As long as PHP is coded correctly and security is done right it is one of the most reliable
web languages there is. The only downside is that when it comes to very large web sites or
applications PHP can falter a bit. PHP is used more than any other back-end language at the
moment, but most larger sites use other back-end languages combined with PHP instead to
make up for it.
D. Cost
The two things that seem to affect the cost of PHP the most (although they may be
indirect) are difficulty of debugging and reputation of the “open source” solution. Debugging
in PHP can be fairly difficult relative to other programming languages. It has tools that you
can work with, but with more complicated bugs the coder might just have to guess where
the issue is.
PHP also has a reputation from big businesses as being the lesser “open source” solution
when competing with J2EE (java) and .NET web back-ends. This can lead businesses to think
they will lose money on the sales end if they choose to use PHP.
IV. Appendices
1.
<!--include /text/header.html-->
<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
Hey, you are using Netscape!<p>
<!--endif-->
<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
Sorry, that record does not exist<p>
<!--endif exit-->
Welcome <!--$user-->!<p>
You have <!--$index:0--> credits left in your account.<p>
<!--include /text/footer.html-->
2.<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test(); //this code will output ‘B’
?>
3.<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
4.<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
5.
xml_set_element_handler()
xml_set_chatacter_data_handler()
xml_set_processing_instruction_handler()
xml_set_default_handler
xml_set_unparsed_entity_decl_handler()
xml_set_notation_decl_handler()
xml_set_external_entity_ref_handler()
xml_set_start_namespace_decl_handler()
xml_set_end_namespace_decl_handler()
6.<?php
class ReadingList{
protected $stack; protected $limit; public function __construct($limit = 10) { // initialize the stack
$this->stack = array();
// stack can only contain this many items
$this->limit = $limit;
}
public function push($item) { // trap for stack overflow
if (count($this->stack) < $this->limit) { // prepend item to the start of the array
array_unshift($this->stack, $item);
} else { throw new RunTimeException('Stack is full!'); }
}
public function pop() { if ($this->isEmpty()) {
// trap for stack underflow
throw new RunTimeException('Stack is empty!'); } else { // pop item from the start of the array
return array_shift($this->stack); }
}
public function top() { return current($this->stack); }
public function isEmpty() { return empty($this->stack); }
}
7.<?php
class AsyncOperation extends Thread {
public function __construct($arg) {
$this->arg = $arg;
}
public function run() {
if ($this->arg) {
$sleep = mt_rand(1, 10);
printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"),
$this->arg, $sleep);
sleep($sleep);
printf('%s: %s -finish' . "\n", date("g:i:sa"), $this-
>arg);
}
}
}
// Create a array
$stack = array();
//Iniciate Miltiple Thread
foreach ( range("A", "D") as $i ) {
$stack[] = new AsyncOperation($i);
}
// Start The Threads
foreach ( $stack as $t ) {
$t->start();
}
?>
Works Cited
“Assignment Operators.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
“Classes and Objects.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
“Control Structures.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
"Encapsulation." Wikipedia. Wikimedia Foundation. Web. 20 Oct. 2014.
“Event Handlers.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014
“Exceptions.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
“Expressions.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
Guzel, Burak. "Top 15 Best Practices for Writing Super Readable Code." Tutsplus. Web. 20 Oct. 2014.
"Is Php Better than Java, .net or Any Other Language?" Letsbefamous. Web. 20 Oct. 2014.
Kumar, Ajitesh. "Top 10 PHP Code Review Tips." Vitalflux. Web. 20 Oct. 2014.
“Late Static Bindings.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
Lengstorf, Jason. "Object-Oriented PHP for Beginners." Tutsplus. Web. 20 Oct. 2014.
"Namespaces." PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
“PHP.” The PHP Group, 2001-2014. Web. 20 Oct. 2014.
"PHP." Wikipedia. Wikimedia Foundation. Web. 20 Oct. 2014.
“Predefined Variables.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014
Smith, Zachary. "Why Choose PHP Over Other Web Development Languages?" Zachis. Web. 20 Oct.
2014.
Teo, Ignatius. "Data Structures for PHP Devs: Stacks and Queues." Sitepoint. Web. 20 Oct. 2014.
“Types.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
"Usage Statistics and Market Share of PHP for Websites." W3techs. Web. 20 Oct. 2014.
“Variable Scope.” PHP. The PHP Group, 2001-2014. Web. 20 Oct. 2014.
Zambonini, Dan. "The Total Cost of Using PHP?" O'Reilly. Web. 20 Oct. 2014.