Professional Documents
Culture Documents
PHP Introduction
PHP Introduction
Introduction
Server side scripting language Crossplatform language Open source code room for further modifications and refinement Simple ASCII text editors like Notepad can be used for development. Syntax is similar to C language, Perl
Features
PHP is a server-side, cross-platform, HTML embedded scripting language designed specifically for internet related applications. It enables you to create
dynamic web pages graphics on the fly
read files locally and remotely, create an array and create graphs on the fly
Content from a local or remote source can be included into the web page via protocols such as HTTP, HTTPS, FTP, and FTPS
String Manipulation Flow-Control Statements Processing Forms Writing to a File LDAP Authentication Accessing a Database Sessions Parsing XML Creating PDF Files On-the-Fly
CrossPlatform PHP does not use a lot of the system and OS resources so it runs fast. Stable language Performance Many levels of Security to prevent malicious attacks. These security levels can be adjusted in the .ini file Connective abilities
PHP has tons of server interfaces, database interfaces and other modules available.
Apache, IIS, Roxen, and AOLserver. Database interfaces available for MySQL, MS SQL, Informix, Oracle and plenty of others.
PHP community
PHP 5
PHP has new integrated for support for XML. The various functions and classes provided to handle XML in different ways all now use the same underlying library (libxml2). This should make XML features more stable and interoperable. The SQLite SQL library is now bundled with PHP, together with all the functions to work with. PHP 5 supports private and protected methods and properties in classes. Objects passed to functions and methods are now passed by reference which will significantly reduces the likelihood of bugs in object-oriented code. PHP supports static methods and properties, making more advanced object-oriented designs possible. Methods can now be declared to require particular object types. PHP5 now supports abstract classes and interfaces. PHP 5 brings new fundamental improvements with the introduction of the Zend Engine 2. Zend is a scripting engine that sits below the PHP-specific modules. The engine provides significantly enhanced support for objectoriented programming.
PHP in gist
Paradigm: Appeared in: 1995 Typing Discipline: Latest Release: Influenced by: Operationg System: Object Oriented Dynamic, weak 5.2.3, 31 may 2007 C, C++, Java, Python, CGI Cross Platform
PHP vs Perl
PHP is built from the ground-up with database functionality built in, particularly MySQL functionality. Perl is not. PHP code gets embedded into HTML pages, unlike Perl. This makes it very fast to code web pages and fast to deploy a new site, thus speeding up Web development and lowering overall cost of ownership. PHP is secure. Perl scripts tend to have more security holes. This is because PHP has built-in a lot of the internal operations of dealing with web page requests and serving information. PHP is easy to learn in comparison to Perl. PHP code tends to be more consistent and modular than Perl. Perl has the Comprehensive Perl Archive Network (CPAN), and PHP has the PHP Extension and Application Repository (PEAR) its own repository of powerful packages that extend PHPs power.
PHP vs ASP
PHP is cheaper to implement that ASP PHP is faster than ASP. ASP supports multiple programming languages. This architecture is inherently slower and more memory intensive that PHPs model because each ASP language compiler runs in its own process. So when ASP detects a Begin ASP tag it will do a context switch back to the HTML parser. PHP is secure. IIS Server is notorious for its security holes. Coding in PHP is more efficient than in ASP. Typically the same functionality can be accomplished in less code with PHP than with ASP. This is because the HTTP GET and POST variables are created automatically by PHP as global variables, thus eliminating the step of extracting them from the ASP Request object. PHPs HTTP header manipulation functions are easier to use than in ASP.
Varaible Scope
The scope of a variable is the context within which it is defined Local Scope within the function or context(single scope). <?php $a = 1; include 'b.inc'; ?> Global Include between different modules One way of accessing globals: <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } ?>
National Informatics Centre, DIT, Govt. of India
Another way of accessing globals: <?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?>
Static Variables
<?php function Test() { static $a = 0; echo $a; $a++; } ?>
Superglobal Variables
Predefined variables in PHP
$_GET, $_POST, $_ENV, $_SESSION, $_COOKIE
Constants
constants can be defined anywhere in the script without regard to scope. Once a constant is defined, it can never be changed or undefined. The procedure for defining constant is
define(NIC",National Informatics Centre"); // Invalid constant names define("2FOO", "something");
A few "magical" PHP constants: __LINE__ The current line number of the file. __FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances. __FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. __CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. __METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
Assignment
Assign by reference
<?php $foo = 'Bob'; // Assign the value 'Bob' to $foo $bar = &$foo; // Reference $foo via $bar. $bar = "My name is $bar"; // Alter $bar... echo $bar; echo $foo; // $foo is altered too. ?>
isset() language construct can be used to detect if a variable has been already initialized.
Control Structures
If-then-else Ternary operators
(condition ? value_if_true : value_if_false) I
switch ($country) { case India": echo (Language is Hindi"); break; case China": echo (" Language is Chinese "); break; case France": echo (" Language is French "); break; }
National Informatics Centre, DIT, Govt. of India
While ... do
$i = 0; while ($i < 10) { echo $i; $i++; }
Do.. while
$i = 0; do { echo $i ; $i++; } while ($i < 10);
For loop
for ($i = 0; $i < 10;$i++) { echo $i; }
FUNCTIONS:
passing a parameter by value
<?php function calc_weeks ($years) { return $years * 52; } $my_years = 28; echo calc_weeks ($my_years); ?>
passing a parameter by reference
<?php function calc_weeks (&$years) { $my_years += 10; return $my_years * 52; } $my_years = 28; echo calc_weeks ($my_years); ?>
assign a default value to any of the parameters of a function when declaring it.
<?php function calc_weeks ($my_years = 10) { return $my_years * 52; } echo calc_weeks (); ?>
Functions with Variable Parameters: <?php function calc_avg() { $args = func_num_args(); if ($args == 0) return 0; $sum = 0; for ($i = 0; $i < $args; $i++) $sum += func_get_arg($i); return $sum / $args; } echo calc_avg (19, 23, 44, 1231, 2132, 11); National ?> Informatics Centre, DIT, Govt.
of India
Data Types
Type Juggling
Example <?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?>
Data Types
Four scalar types:
integer string Double/float Boolean
NULL
The type NULL is reserved for variables that have not been yet initialized.
Operators
+, -, *, _ Concatation
.
Array
Simple Array
By default, arrays are lists of values indexed by number. Values can be assigned to an array in two ways: with the array() construct or directly using empty square brackets ([]). Arbitary index number
An associative array
An associative array is indexed with strings between the square brackets rather than numbers. The keys in an associative array are strings. $array($key=> $value);
Multidimensional array
A multidimensional array is an array of arrays.
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
Example 1
<?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?>
Example 2
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?>
National Informatics Centre, DIT, Govt. of India
Example 3 (Multidimensional)
<?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 ?>
Array Manipulation
Concatenation of arrays (array_merge) Looping (foreach function, print_r($array),var_dump($array)) Sorting of arrays
sort rsort ksort arsort
National Informatics Centre, DIT, Govt. of India
Objects
Basic Classes
Class is a blue print of object and its capabilities Class definition contains
Variables Functions(methods) constants
Class format
<? php class myPhpClass { var $my_variable; function my_method1(){ echo My first attempt; } function my_method2($param){ $param = $param + $my_variable; } } } $obj1 = new myPhpClass(); $obj1->my_method(); ?>
Protected
Data Accessible only by the class members and the child classes defined.
Public
Data accessed from anywhere within the script.
Features
Type Hinting
Instanceof()
Cloning
New instance of current object
--clone() method for only copying the required elements
Class constants
Classname::constant
Static methods
Designed to be accessible outside the context of an instantiated object.
Classname::method()
Class inheritance
Single inheritance model
Class childclass extends Parentclass{ }
Advanced classes
Abstract classes and Methods
Superclass that defines the abstract characteristics Assures functionality within a class. Class classname extends class2 implements class3 { }
Interfaces
Special Methods
_construct() _destruct() Getters and Setters
_get() _set() _call() _toString()
Class Autoloading
Dynamic loading of classes as and when required _autoload() Serialize()
_sleep() _wakeup()
Object Serialization
Unserialize(_)
Exceptions Iterators
Related Links
www.php.net/manual/en/ www.zend.com www.phpbuilder.com www.phpfreaks.com www.w3schools.com www.phpdeveloper.org
Reference Books
PHP CookBook by David Sklar and Adam Trachtenberg, 2003 edition. Published by O'Reilly & Associates Beginning PHP5 by David W Mercer, Allan Kent, Steven D Nowicki, David Mercer, Dan Squier, Wankyu Choi, 2004 Edition. Published byWiley Publication Inc. Application Development with Oracle & PHP on Linux for beginners by Ivan Bayross and Sharanam Shah, First Edition. Published by Shroff Publishers and Distributors, Mumbai Programming PHP Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Thank You.