SlideShare uma empresa Scribd logo
1 de 101
Baixar para ler offline
PHP
What is PHP? 
PHP(recursive acronym forPHP: Hypertext Pre-processor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. 
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Example</title> </head> <body> <?phpecho"Hi,I'maPHPscript!"; ?> </body> </html> 
www.facebook.com/VineetOO7
The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. 
Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours. 
WHATISPHP? 
Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). 
The PHP code is enclosed in specialstart and end processing instructions<?phpand?>that allow you to jump into and out of "PHP mode." 
What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. 
www.facebook.com/VineetOO7
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more 
There are three main areas where PHP scripts are used. 
Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. 
Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron(on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. 
Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. 
WHATCANPHPDO? 
www.facebook.com/VineetOO7
PHP can beusedon all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, IIS, and many others. And this includes any web server that can utilize the FastCGIPHP binary, like lighttpdand nginx. PHP works as either a module, or as a CGI processor. 
So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming (OOP), or a mixture of them both. 
One of the strongest and most significant features in PHP is its support for awide range of databases. Writing a database-enabled web page is incredibly simple using one of the database specific extensions (e.g., formysql) 
WHATCANPHPDO? 
www.facebook.com/VineetOO7
Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. 
PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages. 
Example #1 Our first PHP script:hello.php 
<html> <head> <title>PHPTest</title> </head> <body> <?phpecho'<p>HelloWorld</p>';?> </body> </html> 
EXAMPLE 
Hello.html 
<html> 
<head> 
<title>PHP Test</title> 
</head> 
<body> 
<p> Hello World </p> 
</body> 
</html> 
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display:Hello Worldusing the PHPecho()statement. 
www.facebook.com/VineetOO7
Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is$_SERVER['HTTP_USER_AGENT']. 
$_SERVERis a special reserved PHP variable that contains all web server information. It is known as a superglobal 
<?phpecho$_SERVER['HTTP_USER_AGENT']; ?> 
EXAMPLE 
now you must be thinking what is $_SERVER? 
www.facebook.com/VineetOO7
LANGUAGEBASIC 
•PHP tags 
•Instruction separation 
•Comments 
PHP tags 
When PHP parses a file, it looks for opening and closing tags, which are<?phpand?>which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. 
PHP also allows for short tags<?and?>(which are discouraged because they are only available if enabled withshort_open_tagphp.iniconfiguration file directive, or if PHP was configured with the--enable-short-tags option. 
If a file is pure PHP code, it is preferable omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines after PHP closing tag which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script. 
www.facebook.com/VineetOO7
LANGUAGEBASIC 
2.<scriptlanguage="php"> echo„is it good to write code like this...? No idon't think so.'; </script> 
3.<?echo„this is short php tag to use echoing (print ) ';?> 
4.<?=”it‟s pretty good ! But this looks like Java Server Page‟s expression tag...”?> 
1.<?phpecho'this is php ,doyou likethis ?';?> 
one and two are both always available, example one is the most commonly used, and recommended, of the two. 
Short tags (example three) are only available when they are enabled via theshort_open_tagphp.iniconfiguration file directive, or if PHP was configured with the--enable-short-tagsoption. 
ASPstyle tags (example four) are only available when they are enabled via theasp_tagsphp.iniconfiguration file directive. 
www.facebook.com/VineetOO7
•<?phpecho'Thisisatest'; ?> 
•<?echo'Thisisatest'?> 
•<?phpecho'Weomittedthelastclosingtag'; 
Instruction separation 
As in C or Perl, PHP requires and other programming language instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present. 
LANGUAGEBASIC 
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when usinginclude()orrequire(). 
Include() or require() we‟ll discuss a bit later in this session 
www.facebook.com/VineetOO7
Comments 
LANGUAGEBASIC 
PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example: 
<?phpecho‟good morning Alpana..';//Thisisaone-linec++stylecomment/*Thisisamultilinecommentyetanotherlineofcomment*/ echo”Thisisyetanothertest”; echo'OneFinalTest';#Thisisaone-lineshell-stylecomment?> 
www.facebook.com/VineetOO7
Types 
LANGUAGEBASIC 
PHP supports these primitive types 
boolean 
integer 
Float 
string 
array 
object 
resource 
NULL 
Some examples: 
To forcibly convert a variable to a certain type, eithercastthe variable or use thesettype()function on it. 
<?php$a_bool=TRUE;//aboolean$a_str="foo";//astring$a_str2='foo';//astring$an_int=12;//anintegerechogettype($a_bool);//printsout:booleanechogettype($a_str);//printsout:string//Ifthisisaninteger,incrementitbyfourif(is_int($an_int)){ $an_int+=4; } //If$a_boolisastring,printitout//(doesnotprintoutanything) if(is_string($a_bool)){ echo"String:$a_bool"; } ?> 
Two compound types: 
special types: 
Four scalar types: 
Php supports some more pseudo type like mixed , number , callbackbut for the time being the these are sufficient 
www.facebook.com/VineetOO7
void 
voidas a return type means that the return value is useless.voidin a parameter list means that the function doesn't accept any parameters. 
mixed 
mixedindicates that a parameter may accept multiple (but not necessarily all) types. 
gettype()for example will accept all PHP types, 
number 
numberindicates that a parameter can be eitherintegerorfloat. 
... 
$...in function prototypes meansand so on. This variable name is used when a function can take an endless number of arguments. 
LANGUAGEBASIC 
www.facebook.com/VineetOO7
LANGUAGEBASIC 
Abooleanexpresses a truth value. It can be eitherTRUEorFALSE. 
Booleans 
This is the simplest type. 
To specify abooleanliteral, use the keywordsTRUEorFALSE. Both are case-insensitive. 
Typically, the result of anoperatorwhich returns abooleanvalue is passed on to acontrol structure. 
<?php$foo=True;//assignthevalueTRUEto$foo?> 
<?php//==isanoperatorwhichtests//equalityandreturnsabooleanif($action=="show_version"){ echo"Theversionis1.23"; } //thisisnotnecessary... if($show_separators==TRUE){ echo"<hr>n"; } //...becausethiscanbeusedwithexactlythesamemeaning: if($show_separators){ echo"<hr>n"; } ?> 
www.facebook.com/VineetOO7
Converting to boolean 
LANGUAGEBASIC 
To explicitly convert a value toboolean, use the(bool)or(boolean)casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires abooleanargument. 
When converting toboolean, the following values are consideredFALSE: 
•thebooleanFALSEitself 
•theinteger0 (zero) 
•thefloat0.0 (zero) 
•the emptystring, and thestring"0" 
•anarraywith zero elements 
•anobjectwith zero member variables (PHP 4 only) 
•the special typeNULL(including unset variables) 
•SimpleXMLobjects created from empty tags 
Every other value is consideredTRUE 
<?phpvar_dump((bool)"");//bool(false) var_dump((bool)1);//bool(true) var_dump((bool)-2);//bool(true) var_dump((bool)"foo");//bool(true) var_dump((bool)2.3e5);//bool(true) var_dump((bool)array(12));//bool(true) var_dump((bool)array());//bool(false) var_dump((bool)"false");//bool(true) ?> 
www.facebook.com/VineetOO7
Integers 
Anintegeris a number of the set ℤ= {..., -2, -1, 0, 1, 2, ...}. 
Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (-or +). 
To use octal notation, precede the number with a0(zero). To use hexadecimal notation precede the number with0x. 
Example #1 Integer literals 
<?php$a=1234;//decimalnumber$a=-123;//anegativenumber$a=0123;//octalnumber(equivalentto83decimal) $a=0x1A;//hexadecimalnumber(equivalentto26decimal) ?> 
The size of anintegeris platform-dependent, 
Converting to integer 
To explicitly convert a value tointeger, use either the(int)or(integer)casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires anintegerargument. A value can also be converted tointegerwith theintval()function. 
www.facebook.com/VineetOO7
Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes: 
<?php$a=1.234; $b=1.2e3; $c=7E-10; ?> 
Comparing floats 
As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations. 
To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations. 
$aand$bare equal to 5 digits of precision. 
Formally: 
LNUM [0-9]+ 
DNUM ([0-9]*[.]{LNUM}) | ({LNUM}[.][0-9]*) 
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM}) 
exp. 
<?php$a=1.23456789; $b=1.23456780; $epsilon=0.00001; if(abs($a- $b)<$epsilon){ echo"true"; } ?> 
Floating point numbers 
www.facebook.com/VineetOO7
Strings 
Astringis series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. 
Note:It is no problem for astringto become very large. PHP imposes no boundary on the size of astring; the only limit is the available memory of the computer on which PHP is running. 
Astringliteral can be specified in four different ways: 
single quoted 
double quoted 
heredocsyntax 
nowdocsyntax(since PHP 5.3.0) 
Single quoted 
The simplest way to specify astringis to enclose it in single quotes 
To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (). 
<?phpecho'thisisasimple single quotedstring'; 
www.facebook.com/VineetOO7
Double quoted 
If thestringis enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters: n, r, t 
Heredoc 
A third way to delimitstrings is the heredocsyntax:<<<. After this operator, an identifier is provided, then a newline. Thestringitself follows, and then the same identifier again to close the quotation. 
The closing identifiermustbegin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. 
It is very important to note that the line with the closing identifier must contain no other characters, exceptpossiblya semicolon (;). That means especially that the identifiermay not be indented, and there may not be any spaces or tabs before or after the semicolon. 
Strings 
www.facebook.com/VineetOO7
example 
<?php$str=<<<EODExampleofstringspanningmultiplelinesusingheredocsyntax. EOD; 
/*Morecomplexexample,withvariables.*/ classfoo{ var$foo; var$bar; functionfoo() { $this->foo='Foo'; $this->bar=array('Bar1','Bar2','Bar3'); } } $foo=newfoo(); $name='MyName'; echo<<<EOTMynameis"$name".Iamprintingsome$foo->foo. Now,Iamprintingsome{$foo->bar[1]}. Thisshouldprintacapital'A':x41EOT; ?> 
Strings 
www.facebook.com/VineetOO7
Anarrayin PHP is actually an ordered map. A map is a type that associatesvaluestokeys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. Asarrayvalues can be otherarrays, trees and multidimensionalarrays are also possible. 
Explanation of those data structures is beyond the scope of this manual, but at least some example is provided 
Anarraycan be created using thearray()language construct. It takes any number of comma- separatedkey=>valuepairs as arguments. 
array( 
key => value, 
key2 => value2, 
key3 => value3, 
... 
) 
<?php$array=array( "foo"=>"bar", "bar"=>"foo", ); //asofPHP5.4$array=[ "foo"=>"bar", "bar"=>"foo", ]; ?> 
Arrays 
www.facebook.com/VineetOO7
Additionally the followingkeycasts will occur: 
Strings containing validintegers will be cast to theintegertype. E.g. the key"8"will actually be stored under8. On the other hand"08"will not be cast, as it isn't a valid decimal integer. 
Floats are also cast tointegers, which means that the fractional part will be truncated. E.g. the key8.7will actually be stored under8. 
Boolsare cast tointegers, too, i.e. the keytruewill actually be stored under1and the keyfalseunder0. 
Nullwill be cast to the empty string, i.e. the keynullwill actually be stored under"". 
Arrays andobjectscan notbe used as keys. Doing so will result in a warning:Illegal offset type. 
<?php$array=array( 1=>"a", "1"=>"b", 1.5=>"c", true=>"d", ); var_dump($array); ?> 
Array 
www.facebook.com/VineetOO7
<?phpclassfoo{ functiondo_foo() { echo"Doingfoo."; } } $bar=newfoo; $bar->do_foo(); ?> 
Objects 
To create a newobject, use thenewstatement to instantiate a class: 
Object Initialization 
For more we‟ll be back very sooooooon....... 
www.facebook.com/VineetOO7
Resources 
Aresourceis a special variable, holding a reference to an external resource. Resources are created and used by special functions. 
NULL 
The specialNULLvalue represents a variable with no value.NULLis the only possible value of typeNULL. 
A variable is considered to benullif: 
•it has been assigned the constantNULL. 
•it has not been set to any value yet. 
•it has beenunset(). 
There is only one value of typenull, and that is the case-insensitive constantNULL. 
<?php$var=NULL; ?> 
www.facebook.com/VineetOO7
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if astringvalue is assigned to variable$var,$varbecomesastring. If anintegervalue is then assigned to$var, it becomes aninteger. 
<?php$foo="0";//$fooisstring(ASCII48) $foo+=2;//$fooisnowaninteger(2) $foo=$foo+1.3;//$fooisnowafloat(3.3) $foo=5+"10LittlePiggies";//$fooisinteger(15) $foo=5+"10SmallPigs";//$fooisinteger(15) ?> 
Type Juggling 
www.facebook.com/VineetOO7
The casts allowed are: 
•(int), (integer) -cast tointeger 
•(bool), (boolean) -cast toboolean 
•(float), (double), (real) -cast tofloat 
•(string) -cast tostring 
•(array) -cast toarray 
•(object) -cast toobject 
•(unset) -cast toNULL(PHP 5) 
<?php$foo=10;//$fooisaninteger$bar=(boolean)$foo;//$barisaboolean?> 
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. 
Type Casting 
www.facebook.com/VineetOO7
Variables 
Basics 
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. 
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores 
By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. 
<?php$var='Bob'; $Var='Joe'; echo"$var,$Var";//outputs"Bob,Joe" $4site='notyet';//invalid;startswithanumber$_4site='notyet';//valid;startswithanunderscore$täyte='mansikka';//valid;'ä'is(Extended)ASCII228. ?> 
www.facebook.com/VineetOO7
To assign by reference, simply prependan ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice: 
<?php$foo='Bob';//Assignthevalue'Bob'to$foo$bar=&$foo;//Reference$foovia$bar. $bar="Mynameis$bar";//Alter$bar... echo$bar; echo$foo;//$fooisalteredtoo. ?> 
Variables 
www.facebook.com/VineetOO7
PHP provides a large number of predefined variables to any script which it runs. 
Variable scope 
<?php$a=1;/*globalscope*/ functiontest() { echo$a;/*referencetolocalscopevariable*/ } test(); ?> 
Usingglobal 
<?php$a=1; $b=2; functionSum() { global$a,$b; $b=$a+$b; } Sum(); echo$b; // 3?> 
Predefined Variables 
www.facebook.com/VineetOO7
Using$GLOBALSinstead of global 
<?php$a=1; $b=2; functionSum() { $GLOBALS['b']=$GLOBALS['a']+$GLOBALS['b']; } Sum(); echo$b; ?> 
www.facebook.com/VineetOO7
The$GLOBALSarray is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how$GLOBALSexists in any scope, this is because$GLOBALSis asuperglobal. 
Example demonstrating superglobalsand scope 
<?phpfunctiontest_global() { //Mostpredefinedvariablesaren't"super"andrequire//'global'tobeavailabletothefunctionslocalscope. global$HTTP_POST_VARS; echo$HTTP_POST_VARS['name']; //Superglobalsareavailableinanyscopeanddo//notrequire'global'.Superglobalsareavailable//asofPHP4.1.0,andHTTP_POST_VARSisnow//deemeddeprecated. echo$_POST['name']; } ?> 
www.facebook.com/VineetOO7
Another important feature of variable scoping is thestaticvariable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example: 
<?phpfunctiontest() { $a=0; echo$a; $a++; } ?> 
Now,$ais initialized only in first call of function and every time thetest()function is called it will print the value of$aand increment it. 
<?phpfunctiontest() { static$a=0; echo$a; $a++; } ?> 
This function is quite useless since every time it is called it sets$ato0and prints0. The$a++ which increments the variable serves no purpose since as soon as the function exits the$avariable disappears 
Usingstaticvariables 
www.facebook.com/VineetOO7
Declaring static variables 
<?phpfunctionfoo(){ static$int=0;//correctstatic$int=1+2;//wrong(asitisanexpression) static$int=sqrt(121);//wrong(asitisanexpressiontoo) $int++; echo$int; } ?> 
Note: 
Static declarations are resolved in compile-time. 
www.facebook.com/VineetOO7
<?php$$a='world'; ?> 
Sometimes it is convenient to be able to have variable variablenames. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as: 
A variable variabletakes the value of a variable and treats that as the name of a variable. In the above example,hello, can be used as the name of a variable by using two dollar signs. i.e. At this point two variables have been defined and stored in the PHP symbol tree:$awith contents "hello" and$hellowith contents "world". Therefore, this statement: 
<?php$a='hello'; ?> 
<?phpecho"$a${$a}"; ?> 
produces the exact same output ,they both produce:hello world. 
<?phpecho"$a$hello"; ?> 
Variable variables 
www.facebook.com/VineetOO7
Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as$foo->$bar, then the local scope will be examined for$barand its value will be used as the name of the property of$foo. This is also true if$baris an array access. 
The above example will output: 
I am bar. I am bar. 
<?phpclassfoo{ var$bar='Iambar.'; } $foo=newfoo(); $bar='bar'; $baz=array('foo','bar','baz','quux'); echo$foo->$bar."n"; echo$foo->$baz[1]."n"; ?> 
Example: Variable property example 
www.facebook.com/VineetOO7
Variables From External Sources 
HTML Forms (GET and POST) 
When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example: 
<form action="foo.php" method="post"> 
Name: <input type="text" name="username" /><br/> 
Email: <input type="text" name="email" /><br/> 
<input type="submit" name="submit" value="Submit me!" /> 
</form> 
<?phpecho$_POST['username']; echo$_REQUEST['username']; import_request_variables('p','p_'); echo$p_username; echo$HTTP_POST_VARS['username']; echo$username; ?> 
www.facebook.com/VineetOO7
Constants 
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except formagic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. 
Valid and invalid constant names 
<?php//Validconstantnamesdefine("FOO","something"); define("FOO2","somethingelse"); define("FOO_BAR","somethingmore"); //Invalidconstantnamesdefine("2FOO","something"); //Thisisvalid,butshouldbeavoided: //PHPmayonedayprovideamagicalconstant//thatwillbreakyourscriptdefine("__FOO__","something"); ?> 
Defining Constants using theconstkeyword 
<?php//WorksasofPHP5.3.0constCONSTANT='HelloWorld'; echoCONSTANT; ?> 
www.facebook.com/VineetOO7
Operators 
An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value 
www.facebook.com/VineetOO7
Control Structures 
•if 
•else 
•elseif/else if 
•while 
•do-while 
•for 
•foreach 
•break 
•continue 
•switch 
•Return 
•Include 
•include_once 
Skip the content... 
www.facebook.com/VineetOO7
Functions 
User-defined functions 
Function arguments 
Returning values 
Variable functions(skiped) 
Internal (built-in) functions 
Anonymous functions 
Pseudo code to demonstrate function uses 
<?phpfunctionfoo($arg_1,$arg_2,/*...,*/$arg_n) { echo"Examplefunction.n"; return$retval; } ?> 
User-defined functions 
A function may be defined using syntax such as the following: 
www.facebook.com/VineetOO7
Conditional functions 
<?php$makefoo=true; /*Wecan'tcallfoo()fromhere 
sinceitdoesn'texistyet, butwecancallbar()*/ bar(); if($makefoo){ functionfoo() { echo"Idon'texistuntilprogram 
executionreachesme.n"; } } 
/*Nowwecansafelycallfoo() since$makefooevaluatedtotrue*/ if($makefoo)foo(); functionbar() { echo"Iexistimmediatelyuponprogramstart.n"; } ?> 
www.facebook.com/VineetOO7
Functions within functions 
<?phpfunctionfoo() { functionbar() { echo"Idon'texistuntilfoo()iscalled.n"; } } /*Wecan'tcallbar()yetsinceitdoesn'texist.*/ foo(); /*Nowwecancallbar(), foo()'sprocessinghasmadeitaccessible.*/ bar(); ?> All functions and classes in PHP have the global scope -they can be called outside a function even if they were defined inside and vice versa. 
PHP does not support function overloading, nor is it possible to undefineor redefine previously-declared functions. 
Note:Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration. 
www.facebook.com/VineetOO7
information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right. 
Function arguments 
PHP supports passing arguments by value (the default),passing by reference, anddefault argument values.Variable-length argument listsare also supported, 
Passing arrays to functions 
<?phpfunctiontakes_array($input) { echo"$input[0]+$input[1]=",$input[0]+$input[1]; } ?> 
Passing function parameters by reference 
<?phpfunctionadd_some_extra(&$string) { $string.='andsomethingextra.'; } $str='Thisisastring,'; add_some_extra($str); echo$str;//outputs'Thisisastring,andsomethingextra.' ?> 
www.facebook.com/VineetOO7
Use of default parameters in functions 
Default argument values 
A function may define C++-style default values for scalar arguments as follows: 
<?phpfunctionmakecoffee($type="cappuccino") { return"Makingacupof$type.n"; } echomakecoffee(); echomakecoffee(null); echomakecoffee("espresso"); ?> 
The above example will output: 
Making a cup of cappuccino. 
Making a cup of . 
Making a cup of espresso. 
www.facebook.com/VineetOO7
PHP has support for variable-length argument lists in user-defined functions. This is really quite easy, using thefunc_num_args(),func_get_arg(), andfunc_get_args()functions. 
func_num_args—Returns the number of arguments passed to the function 
func_num_args()example 
<?phpfunctionfoo() { $numargs=func_num_args(); echo"Numberofarguments:$numargsn"; } foo(1,2,3);// 3?> 
Number of arguments: 3 
Variable-length argument lists 
No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal. 
www.facebook.com/VineetOO7
func_get_arg—Return an item from the argument list 
func_get_arg()example 
<?phpfunctionfoo() { $numargs=func_num_args(); echo"Numberofarguments:$numargs<br/>n"; if($numargs>=2){ echo"Secondargumentis:".func_get_arg(1)."<br/>n"; } } foo(1,2,3); ?> 
func_get_args—Returns an array comprising a function's argument list 
<?phpfunctionfoo() { $numargs=func_num_args(); echo"Numberofarguments:$numargs<br/ >n"; if($numargs>=2){ echo"Secondargumentis:".func_get_arg(1)."<br/>n"; } 
$arg_list=func_get_args(); for($i=0;$i<$numargs;$i++){ echo"Argument$iis:".$arg_list[$i]."<br/>n"; } } foo(1,2,3); ?> 
www.facebook.com/VineetOO7
Variable functions 
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. 
Variable function example 
<?phpfunctionfoo(){ echo"Infoo()<br/>n"; } functionbar($arg=„ „) { echo"Inbar();argumentwas'$arg'.<br/> n"; } //Thisisawrapperfunctionaroundechofunctionechoit($string) { echo$string; } 
$func='foo'; $func();//Thiscallsfoo() $func='bar'; $func('test');//Thiscallsbar() $func='echoit'; $func('test');//Thiscallsechoit() ?> 
www.facebook.com/VineetOO7
Anonymous functions 
Anonymous functions, also known asclosures, allow the creation of functions which have no specified name. They are most useful as the value ofcallbackparameters, but they have many other uses. 
Anonymous function variable assignment example 
<?php$greet=function($name) { printf("Hello%srn",$name); }; $greet('World'); $greet('PHP'); ?> 
www.facebook.com/VineetOO7
OBJECT-ORIENTED-PROGRAMMING 
Object: Repository of data. 
Milk 
Jam 
Honey 
Bread 
Biscuits 
myList 
myList is an object of classShoppingList 
Terminology 
Class: Type of object 
ShoppingList 
ShoppingCart 
For different types of objects the methodsof putting milk in them vary. 
Method: 
Procedure or function that operates on an object or on a class of objects. 
Milk 
Jam 
myList 
addItem(Honey) 
myList 
myShoppingCart 
www.facebook.com/VineetOO7
OBJECT-ORIENTED-PROGRAMMING 
Terminology 
Polymorphism: 
One method call can work on several different classes of objects, even if the classes need different implementations e.g. “addItem” method on every kind of List, even though adding item to ShoppingList is very different from adding milk to ShoppingCart. 
This is done using dynamic method 
Object Oriented: 
Each object knows its class and knows which methods work on that class. Each ShoppingList and ShoppingCart knows which “addItem” method it should use. 
Inheritance: 
A class can inherit properties from a more general class. ShoppingList inherits from List class the property of storing a sequence of items. 
www.facebook.com/VineetOO7
class 
Basic class definitions begin with the keywordclass, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. 
The class name can be any valid label which is a not a PHPreserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. 
A class may contain its ownconstants,variables(called "properties"), and functions (called "methods"). 
Simple Class definition 
<?phpclassSimpleClass{ //propertydeclarationpublic$var='adefaultvalue„; //methoddeclarationpublicfunctiondisplayVar(){ echo$this->var; } } ?> 
www.facebook.com/VineetOO7 
The Basics
To create an instance of a class, thenewkeyword must be used. An object will always be created unless the object has aconstructordefined that throws anexceptionon error. Classes should be defined before instantiation (and in some cases this is a requirement). 
<?php$instance=newSimpleClass(); 
Object Assignment 
<?php$instance=newSimpleClass(); $assigned=$instance; $reference=&$instance; $instance->var='$assignedwillhavethisvalue'; $instance=null;//$instanceand$referencebecomenullvar_dump($instance); var_dump($reference); var_dump($assigned); ?> 
www.facebook.com/VineetOO7 
new
The inherited methods and properties can be overridden by redeclaringthem with the same name defined in the parent class. However, if the parent class has defined a method asfinal, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them withparent::. 
When overriding methods, the parameter signature should remain the same 
Simple Class Inheritance 
<?phpclassExtendClassextendsSimpleClass{ //RedefinetheparentmethodfunctiondisplayVar() { echo"Extendingclassn"; parent::displayVar(); } } $extended=newExtendClass(); $extended->displayVar(); ?> 
www.facebook.com/VineetOO7 
extends 
A class can inherit the methods and properties of another class by using the keywordextendsin the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywordspublic,protected, orprivate, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated 
property declarations 
<?phpclassSimpleClass{ //invalidpropertydeclarations: public$var1='hello'.'world'; public$var2=<<<EODhelloworldEOD; public$var3=1+2; public$var4=self::myStaticMethod( ); public$var5=$myVar; 
//validpropertydeclarations: public$var6=myConstant; public$var7=array(true,false); //ThisisallowedonlyinPHP5.3.0andlater. public$var8=<<<'EOD'helloworldEOD; } ?> 
www.facebook.com/VineetOO7 
Properties
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the$symbol to declare or use them. 
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call. 
Defining and using a constant 
<?phpclassMyClass{ constconstant='constantvalue'; functionshowConstant(){ echoself::constant."n"; } } 
echoMyClass::constant."n"; $classname="MyClass"; echo$classname::constant."n";//AsofPHP5.3.0$class=newMyClass(); $class->showConstant(); echo$class::constant."n";//AsofPHP5.3.0?> 
www.facebook.com/VineetOO7 
Class Constants
Constructors and Destructors 
void__construct([mixed$args[,$...]] ) 
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. 
Note:Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call toparent::__construct()within the child constructor is required. 
Constructor 
Its slightly differ from java or other Object Oriented programming language.. 
using new unified constructors 
<?phpclassBaseClass{ function__construct(){ print"InBaseClassconstructorn"; } } 
classSubClassextendsBaseClass{ function__construct(){ parent::__construct(); print"InSubClassconstructorn"; } } 
$obj=newBaseClass(); $obj=newSubClass(); ?> 
www.facebook.com/VineetOO7
Constructors in namespacedclasses 
<?phpnamespaceFoo; classBar{ publicfunctionBar(){ //treatedasconstructorinPHP5.3.0-5.3.2//treatedasregularmethodasofPHP5.3.3} } ?> 
www.facebook.com/VineetOO7
Destructor Example 
Destructor 
void__destruct(void) 
PHP 5 introduces a destructor concept similar to that of other object- oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence 
Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly callparent::__destruct()in the destructor body. 
The destructor will be called even if script execution is stopped usingexit(). Callingexit()in a destructor will prevent the remaining shutdown routines from executing. 
www.facebook.com/VineetOO7 
<?phpclassMyDestructableClass{ function__construct(){ print"Inconstructorn"; $this->name="MyDestructableClass"; } function__destruct(){ print"Destroying".$this->name."n"; } } $obj=newMyDestructableClass(); ?>
Property declaration 
/** *DefineMyClass2*/ classMyClass2extendsMyClass{ //Wecanredeclarethepublicandprotectedmethod,butnotprivateprotected$protected='Protected2'; functionprintHello() { echo$this->public; echo$this->protected; echo$this->private; } } $obj2=newMyClass2(); echo$obj2->public;//Worksecho$obj2->private;//Undefinedecho$obj2->protected;//FatalError$obj2->printHello(); 
//ShowsPublic,Protected2,Undefined?> 
<?php/** *DefineMyClass*/ classMyClass{ public$public='Public'; 
var$default = „public‟; protected$protected='Protected'; private$private='Private'; functionprintHello() { echo$this->public; echo$this->protected; echo$this->private; } } $obj=newMyClass(); 
echo$obj->public;//Worksecho$obj->protected;//FatalErrorecho$obj->private;//FatalError$obj->printHello(); //ShowsPublic,ProtectedandPrivate 
www.facebook.com/VineetOO7
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public. 
<?phpclassMyClass{ //Declareapublicconstructorpublicfunction__construct(){} //DeclareapublicmethodpublicfunctionMyPublic(){} //DeclareaprotectedmethodprotectedfunctionMyProtected(){} //DeclareaprivatemethodprivatefunctionMyPrivate(){} //ThisispublicfunctionFoo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } } 
$myclass=newMyClass; $myclass->MyPublic();//Works$myclass->MyProtected();//FatalError$myclass->MyPrivate();//FatalError$myclass->Foo();//Public,ProtectedandPrivatework 
/** *DefineMyClass2*/ classMyClass2extendsMyClass{ //ThisispublicfunctionFoo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate();//FatalError} } $myclass2=newMyClass2; $myclass2->MyPublic();//Works$myclass2- >Foo2();//PublicandProtectedwork,notPrivate 
www.facebook.com/VineetOO7 
Method Visibility 
Method Declaration
Object Inheritance 
Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another. 
when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality. 
Inheritance Example 
<?phpclassfoo{ publicfunctionprintItem($string) { echo'Foo:'.$string.PHP_EOL; } publicfunctionprintPHP() { echo'PHPisgreat.'.PHP_EOL; 
} } 
classbarextendsfoo{ publicfunctionprintItem($string) { echo'Bar:'.$string.PHP_EOL; } } $foo=newfoo(); $bar=newbar(); $foo->printItem('baz');//Output:'Foo:baz' $foo->printPHP();//Output:'PHPisgreat' $bar->printItem('baz');//Output:'Bar:baz' $bar->printPHP();//Output:'PHPisgreat' ?> 
www.facebook.com/VineetOO7
Scope Resolution Operator (::) 
::from outside the class definition 
<?phpclassMyClass{ constCONST_VALUE='Aconstantvalue'; } $classname='MyClass'; echo$classname::CONST_VALUE;//AsofPHP5.3.0echoMyClass::CONST_VALUE; ?> 
:: from inside the class definition 
<?phpclassOtherClassextendsMyClass{ publicstatic$my_static='staticvar'; publicstaticfunctiondoubleColon(){ echoparent::CONST_VALUE."n"; echoself::$my_static."n"; } } $classname='OtherClass'; echo$classname::doubleColon();//AsofPHP5.3.0OtherClass::doubleColon(); ?> 
www.facebook.com/VineetOO7
Calling a parent's method 
<?phpclassMyClass{ protectedfunctionmyFunc(){ echo"MyClass::myFunc()n"; } } 
classOtherClassextendsMyClass{ //Overrideparent'sdefinitionpublicfunctionmyFunc() { //Butstillcalltheparentfunctionparent::myFunc(); echo"OtherClass::myFunc()n"; } } $class=newOtherClass(); $class->myFunc(); ?> 
www.facebook.com/VineetOO7
Static Keyword 
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can). 
if novisibilitydeclaration is used, then the property or method will be treated as if it was declared aspublic. 
Static properties cannot be accessed through the object using the arrow operator ->. 
Calling non-static methods statically generates anE_STRICTlevel warning. 
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object. 
Static property example 
<?phpclassFoo{ publicstatic$my_static='foo'; publicfunctionstaticValue(){ returnself::$my_static; } } classBarextendsFoo{ publicfunctionfooStatic(){ returnparent::$my_static; } } printFoo::$my_static."n"; $foo=newFoo(); print$foo->staticValue()."n"; print$foo->my_static."n";//Undefined"Property"my_staticprint$foo::$my_static."n"; $classname='Foo'; print$classname::$my_static."n";//AsofPHP5.3.0printBar::$my_static."n"; $bar=newBar(); print$bar->fooStatic()."n"; ?> 
www.facebook.com/VineetOO7
Class Abstraction 
PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature -they cannot define the implementation. 
<?phpabstractclassAbstractClass{ //ForceExtendingclasstodefinethismethodabstractprotectedfunctiongetValue(); abstractprotectedfunctionprefixValue($prefix); 
//CommonmethodpublicfunctionprintOut(){ print$this->getValue()."n"; } } classConcreteClass1extendsAbstractClass{ protectedfunctiongetValue(){ return"ConcreteClass1"; } publicfunctionprefixValue($prefix){ return"{$prefix}ConcreteClass1“;} 
} 
classConcreteClass2extendsAbstractClass{ publicfunctiongetValue(){ return"ConcreteClass2"; } publicfunctionprefixValue($prefix){ return"{$prefix}ConcreteClass2"; } } $class1=newConcreteClass1; $class1->printOut(); echo$class1->prefixValue('FOO_')."n"; $class2=newConcreteClass2; $class2->printOut(); echo$class2->prefixValue('FOO_')."n"; ?> 
ConcreteClass1 
FOO_ConcreteClass1 
ConcreteClass2 
FOO_ConcreteClass2 
www.facebook.com/VineetOO7
Object Interfaces 
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. 
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined. 
All methods declared in an interface must be public, this is the nature of an interface. 
implements 
To implement an interface, theimplementsoperator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma. 
Interfaces can be extended like classes using theextendsoperator. 
The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error. 
Constants 
Its possible for interfaces to have constants. Interface constants works exactly likeclass constantsexcept they cannot be overridden by a class/interface that inherits it. 
www.facebook.com/VineetOO7
Interface example 
<?php//Declaretheinterface'iTemplate'interfaceiTemplate{ publicfunctionsetVariable($name,$var); publicfunctiongetHtml($template); } //Implementtheinterface//ThiswillworkclassTemplateimplementsiTemplate{ private$vars=array(); publicfunctionsetVariable($name,$var) { $this->vars[$name]=$var; } publicfunctiongetHtml($template) { foreach($this->varsas$name=>$value){ $template=str_replace('{'.$name.'}',$value, $template); } return$template; } } //Thiswillnotwork//Fatalerror:ClassBadTemplatecontains1abstractmethods//andmustthereforebedeclaredabstract(iTemplate:: getHtml) classBadTemplateimplementsiTemplate{ private$vars=array(); publicfunctionsetVariable($name,$var) { $this->vars[$name]=$var; } } ?> 
www.facebook.com/VineetOO7
Extendable Interfaces 
<?phpinterfacea{ publicfunctionfoo(); } interfacebextendsa{ publicfunctionbaz(Baz$baz); } //Thiswillworkclasscimplementsb{ publicfunctionfoo() { } publicfunctionbaz(Baz$baz) { } } //Thiswillnotworkandresultinafatalerrorclassdimplementsb{ publicfunctionfoo() { } publicfunctionbaz(Foo$foo) { } } ?> 
www.facebook.com/VineetOO7
Multiple interface inheritance 
<?phpinterfacea{ publicfunctionfoo(); } interfaceb{ publicfunctionbar(); } interfacecextendsa,b{ publicfunctionbaz(); } classdimplementsc{ publicfunctionfoo() { } publicfunctionbar() { } publicfunctionbaz() { } } ?> 
www.facebook.com/VineetOO7
Interfaces with constants 
<?phpinterfacea{ constb='Interfaceconstant'; } //Prints:Interfaceconstantechoa::b; //Thiswillhowevernotworkbecauseitsnotallowedto//overrideconstants. classbimplementsa{ constb='Classconstant'; } ?> 
www.facebook.com/VineetOO7
Overloading 
Overloading in PHP provides means to dynamically "create" properties and methods. 
All overloading methods must be defined aspublic. 
<?phpclassPropertyTest{ /**Locationforoverloadeddata.*/ private$data=array(); /**Overloadingnotusedondeclaredproperties.*/ public$declared=1; /**Overloadingonlyusedonthiswhenaccessedoutsidetheclass. */ private$hidden=2; publicfunction__set($name,$value) { echo"Setting'$name'to'$value'n"; $this->data[$name]=$value; } publicfunction__get($name) { echo"Getting'$name'n"; if(array_key_exists($name, $this->data)){ return$this- >data[$name]; } $trace=debug_backtrace(); trigger_error( 'Undefinedpropertyvia__get():'.$name. 'in'.$trace[0]['file']. 'online'.$trace[0][ 'line'], E_USER_NOTICE); returnnull; } 
www.facebook.com/VineetOO7
/**AsofPHP5.1.0*/ publicfunction__isset($name) { echo"Is'$name'set?n"; returnisset($this- >data[$name]); } /**AsofPHP5.1.0*/ publicfunction__unset($name) { echo"Unsetting'$name'n"; unset($this->data[$name]); } /**Notamagicmethod,justhereforexample.*/ publicfunctiongetHidden() { return$this->hidden; } } echo"<pre>n"; $obj=newPropertyTest; $obj->a=1; echo$obj->a."nn"; var_dump(isset($obj->a)); unset($obj->a); var_dump(isset($obj->a)); echo"n"; echo$obj->declared."nn"; echo"Let'sexperimentwiththeprivatepropertynamed'hidden':n"; echo"Privatesarevisibleinsidetheclass,so__get()notused...n" ; echo$obj->getHidden()."n"; echo"Privatesnotvisibleoutsideofclass,so__get()isused...n"; echo$obj->hidden."n"; ?> 
www.facebook.com/VineetOO7
Method overloading 
publicmixed__call(string$name,array$arguments) 
public staticmixed__callStatic(string$name,array$arguments) 
__call()is triggered when invoking inaccessible methods in an object context. 
__callStatic()is triggered when invoking inaccessible methods in a static context. 
The$nameargument is the name of the method being called. The$argumentsargument is an enumerated array containing the parameters passed to the$name'edmethod. 
Overloading methods via the__call()and__callStatic()methods 
<?phpclassMethodTest{ publicfunction__call($name,$arguments) { //Note:valueof$nameiscasesensitive. echo"Callingobjectmethod'$name'" .implode(',',$arguments)."n"; } /**AsofPHP5.3.0*/ publicstaticfunction__callStatic($name,$arguments) { //Note:valueof$nameiscasesensitive. echo"Callingstaticmethod'$name'" .implode(',',$arguments)."n"; } } $obj=newMethodTest; $obj->runTest('inobjectcontext'); MethodTest::runTest('instaticcontext');//AsofPHP5.3.0?> 
The above example will output: 
Calling object method 'runTest' in object context Calling static method 'runTest' in static context 
www.facebook.com/VineetOO7
Object Iteration 
PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example aforeachstatement. By default, allvisibleproperties will be used for the iteration 
<?phpclassMyClass{ public$var1='value1'; public$var2='value2'; public$var3='value3'; protected$protected='protectedvar'; private$private='privatevar'; functioniterateVisible(){ echo"MyClass::iterateVisible:n"; foreach($thisas$key=>$value) { print"$key=>$valuen"; } } } $class=newMyClass(); foreach($classas$key=>$value){ print"$key=>$valuen"; } echo"n"; $class->iterateVisible(); ?> 
The above example will output: 
var1 => value 1 var2 => value 2 var3 => value 3 MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected varprivate => private var 
www.facebook.com/VineetOO7
Object Iteration implementing Iterator 
<?phpclassMyIteratorimplementsIterator{ private$var=array(); publicfunction__construct($array) { if(is_array($array)){ $this->var=$array; } } publicfunctionrewind() { echo"rewindingn"; reset($this->var); } publicfunctioncurrent() { $var=current($this->var); echo"current:$varn"; return$var; } publicfunctionkey() { $var=key($this->var); echo"key:$varn"; return$var; } publicfunctionnext() { $var=next($this->var); echo"next:$varn"; return$var; } publicfunctionvalid() { $key=key($this->var); $var=($key!==NULL&&$key!== FALSE); echo"valid:$varn"; return$var; } } $values=array(1,2,3); $it=newMyIterator($values); foreach($itas$a=>$b) { print"$a:$bn"; } ?> 
rewinding valid: 1 current: 1 key: 0 0: 1 next: 2 valid: 1 current: 2 key: 1 1: 2 next: 3 valid: 1 current: 3 key: 2 2: 3 next: valid: 
www.facebook.com/VineetOO7
Final Keyword 
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. 
Final methods example 
<?phpclassBaseClass{ publicfunctiontest(){ echo"BaseClass::test()calledn"; } finalpublicfunctionmoreTesting(){ echo"BaseClass::moreTesting()calledn"; } } classChildClassextendsBaseClass{ publicfunctionmoreTesting(){ echo"ChildClass::moreTesting()calledn"; } } //ResultsinFatalerror:CannotoverridefinalmethodBaseClass::moreTesting() ?> 
Final class example 
<?phpfinalclassBaseClass{ publicfunctiontest(){ echo"BaseClass::test()calledn"; } //Hereitdoesn'tmatterifyouspecifythefunctionasfinalornotfinalpublicfunctionmoreTesting(){ echo"BaseClass::moreTesting()calledn"; } } classChildClassextendsBaseClass{ } //ResultsinFatalerror:ClassChildClassmaynotinheritfromfinalclass(BaseClass) ?> 
www.facebook.com/VineetOO7
Object Cloning 
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, 
An object copy is created by using the clone keyword (which calls the object's__clone()method if possible). An object's__clone()method cannot be called directly. 
$copy_of_object= clone $object; 
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. 
<?phpclassSubObject{ static$instances=0; public$instance; publicfunction__construct(){ $this->instance=++self::$instances; } publicfunction__clone(){ $this->instance=++self::$instances; } } classMyCloneable{ public$object1; public$object2; function__clone() { //Forceacopyofthis->object,otherwise//itwillpointtosameobject. $this->object1=clone$this->object1; } } $obj=newMyCloneable(); $obj->object1= newSubObject(); $obj->object2= newSubObject(); $obj2=clone$obj; print("OriginalObject:n"); print_r($obj); print("ClonedObject:n"); print_r($obj2); ?> 
Original Object: MyCloneableObject ( [object1] => SubObjectObject ( [instance] => 1 ) [object2] => SubObjectObject ( [instance] => 2 ) ) Cloned Object: MyCloneableObject ( [object1] => SubObjectObject ( [instance] => 3 ) [object2] => SubObjectObject ( [instance] => 2 ) ) 
www.facebook.com/VineetOO7
Comparing Objects 
In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language). 
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. 
On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class. 
<?phpfunctionbool2str($bool) { if($bool===false){ return'FALSE'; }else{ return'TRUE'; } } functioncompareObjects(&$o1,&$o2) { echo'o1==o2:'.bool2str($o1==$ o2)."n"; echo'o1!=o2:'.bool2str($o1!=$ o2)."n"; echo'o1===o2:'.bool2str($o1=== $o2)."n"; echo'o1!==o2:'.bool2str($o1!== $o2)."n"; } classFlag{ public$flag; functionFlag($flag=true){ $this->flag=$flag; } } 
www.facebook.com/VineetOO7
classOtherFlag{ public$flag; functionOtherFlag($flag=true){ $this->flag=$flag; } } $o=newFlag(); $p=newFlag(); $q=$o; $r=newOtherFlag(); echo"Twoinstancesofthesameclassn"; compareObjects($o,$p); echo"nTworeferencestothesameinstancen"; compareObjects($o,$q); echo"nInstancesoftwodifferentclassesn"; compareObjects($o,$r); ?> 
Two instances of the same class o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : FALSE o1 !== o2 : TRUE Two references to the same instance o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE Instances of two different classes o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE 
www.facebook.com/VineetOO7
Late Static Bindings 
HP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. 
More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the::operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced byself::,parent::,static::, or, if going up in the class hierarchy,forward_static_call(). The functionget_called_class()can be used to retrieve a string with the name of the called class andstatic::introduces its scope 
This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact thatstatic::will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls. 
Limitations ofself:: 
Static references to the current class likeself::or__CLASS__are resolved using the class in which the function belongs, as in where it was defined: 
self::usage 
<?phpclassA{ publicstaticfunctionwho(){ echo__CLASS__; } publicstaticfunctiontest(){ self::who(); } } classBextendsA{ publicstaticfunctionwho(){ echo__CLASS__; } } B::test(); ?> 
The above example will output: 
A 
forward_static_call()-Call a static method 
www.facebook.com/VineetOO7
Late Static Bindings' usage 
Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to referenceBfromtest()in the previous example. It was decided not to introduce a new keyword but rather usestaticthat was already reserved. 
Example #2static::simple usage 
<?phpclassA{ publicstaticfunctionwho(){ echo__CLASS__; } publicstaticfunctiontest(){ static::who();//HerecomesLateStaticBindings} } classBextendsA{ publicstaticfunctionwho(){ echo__CLASS__; } } B::test(); ?> 
The above example will output: 
B 
In non-static contexts, the called class will be the class of the object instance. Since$this->will try to call private methods from the same scope, usingstatic::may give different results. Another difference is thatstatic::can only refer to static properties. 
www.facebook.com/VineetOO7
static::usage in a non-static context 
<?phpclassA{ privatefunctionfoo(){ echo"success!n"; } publicfunctiontest(){ $this->foo(); static::foo(); } } classBextendsA{ /*foo()willbecopiedtoB,henceitsscopewillstillbeAand*thecallbesuccessful*/ } classCextendsA{ privatefunctionfoo(){ /*originalmethodisreplaced;thescopeofthenewoneisC*/ } } $b=newB(); $b->test(); $c=newC(); $c->test();//fails?> 
The above example will output: 
success! success! success! 
Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords likeparent::orself::will forward the calling information. 
www.facebook.com/VineetOO7
Objects and references 
One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples. 
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessorsto find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. 
References and Objects 
<?phpclassA{ public$foo=1; } $a=newA; $b=$a;//$aand$barecopiesofthesameidentifier//($a)=($b)=<id> $b->foo=2; echo$a->foo."n"; $c=newA; $d=&$c;//$cand$darereferences//($c,$d)=<id> $d->foo=2; echo$c->foo."n"; $e=newA; functionfoo($obj){ //($obj)=($e)=<id> $obj->foo=2; } foo($e); echo$e->foo."n"; ?> 
The above example will output: 
2 2 2 
www.facebook.com/VineetOO7
Object Serialization 
Serializing objects -objects in sessions 
serialize()returns a string containing a byte-stream representation of any value that can be stored in PHP.unserialize()can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class. 
In order to be able tounserialize()an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserializethis in another file, an object of class A, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of thespl_autoload_register()function. 
<?php//classa.inc: classA{ public$one=1; publicfunctionshow_one(){ echo$this->one; } } //page1.php: include("classa.inc"); $a=newA; $s=serialize($a); //store$ssomewherewherepage2.phpcanfindit. file_put_contents('store',$s); //page2.php: //thisisneededfortheunserializetoworkproperly. include("classa.inc"); $s=file_get_contents('store'); $a=unserialize($s); //nowusethefunctionshow_one()ofthe$aobject. $a->show_one(); ?> 
www.facebook.com/VineetOO7
Namespaces 
What are namespaces? 
In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. 
For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: 
1.Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants. 
2.Ability to alias (or shorten) Extra_Long_Namesdesigned to alleviate the first problem, improving readability of source code. 
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP: 
<?phpnamespacemyname;//see"DefiningNamespaces"sectionclassMyClass{} functionmyfunction(){} constMYCONST=1; $a=newMyClass; $c=newmynameMyClass;//see"GlobalSpace"section$a=strlen('hi');//see"Usingnamespaces:fallbacktoglobal//function/constant"section$d=namespaceMYCONST;//see"namespaceoperatorand__NAMESPACE__ //constant"section$d=__NAMESPACE__.'MYCONST'; echoconstant($d);//see"Namespacesanddynamiclanguagefeatures"section?> 
www.facebook.com/VineetOO7
Defining namespaces 
Although any valid PHP code can be contained within a namespace, only four types of code are affected by namespaces: classes, interfaces, functions and constants. 
Namespaces are declared using thenamespacekeyword. A file containing a namespace must declare the namespace at the top of the file before any other code 
Declaring a single namespace 
<?phpnamespaceMyProject; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} ?> 
<html> <?phpnamespaceMyProject;//fatalerror-namespacemustbethefirststatementinthescript?> 
The only code construct allowed before a namespace declaration is thedeclarestatement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace: 
www.facebook.com/VineetOO7
Declaring sub-namespaces 
Much like directories and files, PHP namespaces also contain the ability to specify a hierarchy of namespace names. Thus, a namespace name can be defined with sub-levels: 
<?phpnamespaceMyProjectSubLevel; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} ?>Defining multiple namespaces in the same file 
Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. 
<?phpnamespaceMyProject; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} namespaceAnotherProject; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} ?> 
This syntax is not recommended for combining namespaces into a single file. 
www.facebook.com/VineetOO7
Declaring multiple namespaces, bracketed syntax 
<?phpnamespaceMyProject{ constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} } namespaceAnotherProject{ constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} } ?> 
Declaring multiple namespaces and unnamespacedcode 
<?phpnamespaceMyProject{ constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} } namespace{//globalcodesession_start(); $a=MyProjectconnect(); echoMyProjectConnection::start(); } ?> 
www.facebook.com/VineetOO7
/*Unqualifiedname*/ foo();//resolvestofunctionFooBarfoofoo::staticmethod();//resolvestoclassFooBarfoo,methodstaticmethodechoFOO;//resolvestoconstantFooBarFOO/*Qualifiedname*/ subnamespacefoo();//resolvestofunctionFooBarsubnamespacefoosubnamespacefoo::staticmethod();//resolvestoclassFooBarsubnamespacefoo, //methodstaticmethodechosubnamespaceFOO;//resolvestoconstantFooBarsubnamespaceFOO/*Fullyqualifiedname*/ FooBarfoo();//resolvestofunctionFooBarfooFooBarfoo::staticmethod();//resolvestoclassFooBarfoo,methodstaticmethodechoFooBarFOO;//resolvestoconstantFooBarFOO?> 
file1.php 
<?phpnamespaceFooBarsubnamespace; constFOO=1; functionfoo(){} classfoo{ staticfunctionstaticmethod(){} } ?> 
file2.php 
<?phpnamespaceFooBar; include'file1.php'; constFOO=2; functionfoo(){} classfoo{ staticfunctionstaticmethod(){} } 
www.facebook.com/VineetOO7
Using namespaces: Aliasing/Importing 
The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystemsto create symbolic links to a file or to a directory. 
PHP namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. Note that importing a function or constant is not supported. 
In PHP, aliasing is accomplished with theuseoperator. Here is an example showing all 3 kinds of importing: 
importing/aliasing with the use operator 
<?phpnamespacefoo; useMyFullClassnameasAnother; //thisisthesameasuseMyFullNSnameasNSnameuseMyFullNSname; //importingaglobalclassuseArrayObject; $obj=newnamespaceAnother;//instantiatesobjectofclassfooAnother$obj=newAnother;//instantiatesobjectofclassMyFullClassnameNSnamesubnsfunc();//callsfunctionMyFullNSnamesubnsfunc$a=newArrayObject(array(1));//instantiatesobjectofclassArrayObject//withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfooArrayObject?> 
www.facebook.com/VineetOO7
Exception 
PHP 5 has an exception model similar to that of other programming languages. An exception can bethrown, and caught ("catched") within PHP. Code may be surrounded in atryblock, to facilitate the catching of potential exceptions. 
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matchingcatchblock. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." 
Eachtrymust have at least one correspondingcatchblock. Multiplecatchblocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within thetryblock, or when acatchmatching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can bethrown (or re-thrown) within acatchblock. 
<?phpfunctioninverse($x){ if(!$x){ thrownewException('Divisionbyzero.'); } elsereturn1/$x; } try{ echoinverse(5)."n"; echoinverse(0)."n"; }catch(Exception$e){ echo'Caughtexception:',$e- >getMessage(),"n"; } //Continueexecutionecho'HelloWorld'; ?> 
www.facebook.com/VineetOO7
<?phpclassMyExceptionextendsException{} classTest{ publicfunctiontesting(){ try{ try{ thrownewMyException('foo!'); }catch(MyException$e){ /*rethrowit*/ throw$e; } }catch(Exception$e){ var_dump($e->getMessage()); } } } $foo=newTest; $foo->testing(); ?> 
Nested / Custom Exception 
www.facebook.com/VineetOO7
Exception 
Exceptionis the base class for all Exceptions. 
Exception::getMessage()example 
<?phptry{ thrownewException("Someerrormessage"); }catch(Exception$e){ echo$e->getMessage(); } ?> 
The above example will output something similar to: 
Some error message 
Exception::getPrevious()example 
Looping over, and printing out, exception trace. 
<?phpclassMyCustomExceptionextendsException{} functiondoStuff(){ try{ thrownewInvalidArgumentException("Youaredoingitwrong!",112); }catch(Exception$e){ thrownewMyCustomException("Somethinghappend",911,$e); } } try{ doStuff(); }catch(Exception$e){ do{ printf("%s:%d%s(%d)[%s]n",$e->getFile(),$e- >getLine(),$e->getMessage(),$e->getCode(),get_class($e)); }while($e=$e->getPrevious()); } ?> 
The above example will output something similar to: 
/home/bjori/ex.php:8 Something happend(911) [MyCustomException] /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException] 
www.facebook.com/VineetOO7
Protocol support by php 
Filesystem 
ftp 
http 
www.facebook.com/VineetOO7
Cookies 
PHP transparently supportsHTTPcookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using thesetcookie()function. Cookies are part of theHTTPheader, sosetcookie()must be called before any output is sent to the browser. 
Any cookies sent to you from the client will automatically be included into a$_COOKIEauto-global array 
setcookie 
setcookie()defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sentbeforeany output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including<html>and<head>tags as well as any whitespace. 
Once the cookies have been set, they can be accessed on the next page load with the$_COOKIEor$HTTP_COOKIE_VARSarrays. Cookie values also exist in$_REQUEST. 
Http protocol 
www.facebook.com/VineetOO7
<?php$value='somethingfromsomewhere'; setcookie("TestCookie",$value); setcookie("TestCookie",$value,time()+3600);/*expirein1hour*/ setcookie("TestCookie",$value,time()+3600,"/~rasmus/","example.com",1); ?> 
setcookie()send example 
<?php//Printanindividualcookieecho$_COOKIE["TestCookie"]; echo$HTTP_COOKIE_VARS["TestCookie"]; //Anotherwaytodebug/testistoviewallcookiesprint_r($_COOKIE); ?> 
<?php//settheexpirationdatetoonehouragosetcookie("TestCookie","",time()-3600); setcookie("TestCookie","",time()- 3600,"/~rasmus/","example.com",1); ?> 
setcookie()delete 
www.facebook.com/VineetOO7
<?php//setthecookiessetcookie("cookie[three]","cookiethree"); setcookie("cookie[two]","cookietwo"); setcookie("cookie[one]","cookieone"); //afterthepagereloads,printthemoutif(isset($_COOKIE['cookie'])){ foreach($_COOKIE['cookie']as$name=>$value) { $name=htmlspecialchars($name); $value=htmlspecialchars($value); echo"$name:$value<br/>n"; } } ?> 
The above example will output: 
three : cookiethreetwo : cookietwoone : cookieone 
www.facebook.com/VineetOO7
Sessions 
Introduction 
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. 
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. 
The session support allows you to store data between requests in the$_SESSIONsuperglobalarray 
www.facebook.com/VineetOO7
boolsession_start(void) 
session_start()creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. 
session_start—Start new or resume existing session 
page1.php 
<?php//page1.phpsession_start(); echo'Welcometopage#1'; $_SESSION['favcolor']='green'; $_SESSION['animal']='cat'; $_SESSION['time']=time(); //Worksifsessioncookiewasacceptedecho'<br/><ahref="page2.php">page2</a>'; //Ormaybepassalongthesessionid,ifneededecho'<br/><ahref="page2.php?'.SID.'">page2</a>'; ?> 
page2.php 
<?php//page2.phpsession_start(); echo'Welcometopage#2<br/>'; echo$_SESSION['favcolor'];//greenecho$_SESSION['animal'];//catechodate('YmdH:i:s',$_SESSION['time']); //YoumaywanttouseSIDhere,likewedidinpage1.phpecho'<br/><ahref="page1.php">page1</a>'; ?> 
www.facebook.com/VineetOO7
session_regenerate_id 
session_regenerate_id—Update the current session id with a newly generated one 
Asession_regenerate_id()example 
<?phpsession_start(); $old_sessionid=session_id(); session_regenerate_id(); $new_sessionid=session_id(); echo"OldSession:$old_sessionid<br/>"; echo"NewSession:$new_sessionid<br/>"; print_r($_SESSION); ?> 
www.facebook.com/VineetOO7
session_name 
session_name—Get and/or set the current session name 
session_name()returns the name of the current session. Ifnameis given,session_name()will update the session name and return theoldsession name. 
session_name()example 
<?php/*setthesessionnametoWebsiteID*/ $previous_name=session_name("WebsiteID"); echo"Theprevioussessionnamewas$previous_name<br/>"; ?> 
stringsession_name([string$name] ) 
www.facebook.com/VineetOO7

Mais conteúdo relacionado

Mais procurados

Mais procurados (16)

Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Software Design
Software DesignSoftware Design
Software Design
 
Welcome to computer programmer 2
Welcome to computer programmer 2Welcome to computer programmer 2
Welcome to computer programmer 2
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php introduction and configuration
Php introduction and configurationPhp introduction and configuration
Php introduction and configuration
 
Php ppt
Php pptPhp ppt
Php ppt
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web Services
 
Intro to-php-19 jun10
Intro to-php-19 jun10Intro to-php-19 jun10
Intro to-php-19 jun10
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Php hypertext pre-processor
Php   hypertext pre-processorPhp   hypertext pre-processor
Php hypertext pre-processor
 
Php intro
Php introPhp intro
Php intro
 

Destaque

Location Information Supporting Anketell Port Development
Location Information Supporting Anketell Port DevelopmentLocation Information Supporting Anketell Port Development
Location Information Supporting Anketell Port DevelopmentWALISOffice
 
Adnan edit laporan kpm kel 6
Adnan edit laporan kpm kel 6Adnan edit laporan kpm kel 6
Adnan edit laporan kpm kel 6عيني رحمه
 
Data Visualisation - An Introduction
Data Visualisation - An IntroductionData Visualisation - An Introduction
Data Visualisation - An Introductionb1e1n1
 
Utoken 電子幣新趨勢簡體版(有網址)
Utoken 電子幣新趨勢簡體版(有網址)Utoken 電子幣新趨勢簡體版(有網址)
Utoken 電子幣新趨勢簡體版(有網址)ufunmoney
 
Renown Electric Motors & Repair:
Renown Electric Motors & Repair: Renown Electric Motors & Repair:
Renown Electric Motors & Repair: bschmigel
 
Ten Keys for a Happier Life
Ten Keys for a Happier LifeTen Keys for a Happier Life
Ten Keys for a Happier LifeJohnPaul Golino
 
2º eso germanic kingdoms
2º eso germanic kingdoms2º eso germanic kingdoms
2º eso germanic kingdomsdavidpuly
 
Mergers and acquisitionby nissan
Mergers and acquisitionby nissanMergers and acquisitionby nissan
Mergers and acquisitionby nissanvinodsule
 
Group ergonomicsguide
Group ergonomicsguideGroup ergonomicsguide
Group ergonomicsguidelangd6141
 
Flags of New World Slave Risings
Flags of New World Slave RisingsFlags of New World Slave Risings
Flags of New World Slave Risingssknwlton
 
Following/Challenging Conventions: Digipak
Following/Challenging Conventions: DigipakFollowing/Challenging Conventions: Digipak
Following/Challenging Conventions: Digipaktalitha-roberts
 
Template forum pa challenge a #sce2014 1 eit-ict-labs
Template forum pa challenge a #sce2014 1 eit-ict-labsTemplate forum pa challenge a #sce2014 1 eit-ict-labs
Template forum pa challenge a #sce2014 1 eit-ict-labscaregnato
 
內壢火車站
內壢火車站內壢火車站
內壢火車站又瑋 賴
 

Destaque (18)

7 BELLAS ARTES
7 BELLAS ARTES7 BELLAS ARTES
7 BELLAS ARTES
 
Location Information Supporting Anketell Port Development
Location Information Supporting Anketell Port DevelopmentLocation Information Supporting Anketell Port Development
Location Information Supporting Anketell Port Development
 
Adnan edit laporan kpm kel 6
Adnan edit laporan kpm kel 6Adnan edit laporan kpm kel 6
Adnan edit laporan kpm kel 6
 
Data Visualisation - An Introduction
Data Visualisation - An IntroductionData Visualisation - An Introduction
Data Visualisation - An Introduction
 
Utoken 電子幣新趨勢簡體版(有網址)
Utoken 電子幣新趨勢簡體版(有網址)Utoken 電子幣新趨勢簡體版(有網址)
Utoken 電子幣新趨勢簡體版(有網址)
 
Permulin
PermulinPermulin
Permulin
 
Renown Electric Motors & Repair:
Renown Electric Motors & Repair: Renown Electric Motors & Repair:
Renown Electric Motors & Repair:
 
Global warming x mia 2
Global warming x mia 2Global warming x mia 2
Global warming x mia 2
 
Ten Keys for a Happier Life
Ten Keys for a Happier LifeTen Keys for a Happier Life
Ten Keys for a Happier Life
 
Mesjidd
MesjiddMesjidd
Mesjidd
 
2º eso germanic kingdoms
2º eso germanic kingdoms2º eso germanic kingdoms
2º eso germanic kingdoms
 
Mergers and acquisitionby nissan
Mergers and acquisitionby nissanMergers and acquisitionby nissan
Mergers and acquisitionby nissan
 
Group ergonomicsguide
Group ergonomicsguideGroup ergonomicsguide
Group ergonomicsguide
 
Flags of New World Slave Risings
Flags of New World Slave RisingsFlags of New World Slave Risings
Flags of New World Slave Risings
 
Prezentace bez názvu
Prezentace bez názvuPrezentace bez názvu
Prezentace bez názvu
 
Following/Challenging Conventions: Digipak
Following/Challenging Conventions: DigipakFollowing/Challenging Conventions: Digipak
Following/Challenging Conventions: Digipak
 
Template forum pa challenge a #sce2014 1 eit-ict-labs
Template forum pa challenge a #sce2014 1 eit-ict-labsTemplate forum pa challenge a #sce2014 1 eit-ict-labs
Template forum pa challenge a #sce2014 1 eit-ict-labs
 
內壢火車站
內壢火車站內壢火車站
內壢火車站
 

Semelhante a Php (20)

PHP.docx
PHP.docxPHP.docx
PHP.docx
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
PHP
PHPPHP
PHP
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Php1
Php1Php1
Php1
 
Article 01 What Is Php
Article 01   What Is PhpArticle 01   What Is Php
Article 01 What Is Php
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Php1
Php1Php1
Php1
 
Php1
Php1Php1
Php1
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
PHP Lesson
PHP LessonPHP Lesson
PHP Lesson
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
PHP
 PHP PHP
PHP
 
Php unit i
Php unit iPhp unit i
Php unit i
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
Php notes
Php notesPhp notes
Php notes
 

Último

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Último (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 

Php

  • 1. PHP
  • 2. What is PHP? PHP(recursive acronym forPHP: Hypertext Pre-processor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Example</title> </head> <body> <?phpecho"Hi,I'maPHPscript!"; ?> </body> </html> www.facebook.com/VineetOO7
  • 3. The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours. WHATISPHP? Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in specialstart and end processing instructions<?phpand?>that allow you to jump into and out of "PHP mode." What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. www.facebook.com/VineetOO7
  • 4. Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more There are three main areas where PHP scripts are used. Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron(on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. WHATCANPHPDO? www.facebook.com/VineetOO7
  • 5. PHP can beusedon all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, IIS, and many others. And this includes any web server that can utilize the FastCGIPHP binary, like lighttpdand nginx. PHP works as either a module, or as a CGI processor. So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming (OOP), or a mixture of them both. One of the strongest and most significant features in PHP is its support for awide range of databases. Writing a database-enabled web page is incredibly simple using one of the database specific extensions (e.g., formysql) WHATCANPHPDO? www.facebook.com/VineetOO7
  • 6. Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages. Example #1 Our first PHP script:hello.php <html> <head> <title>PHPTest</title> </head> <body> <?phpecho'<p>HelloWorld</p>';?> </body> </html> EXAMPLE Hello.html <html> <head> <title>PHP Test</title> </head> <body> <p> Hello World </p> </body> </html> This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display:Hello Worldusing the PHPecho()statement. www.facebook.com/VineetOO7
  • 7. Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is$_SERVER['HTTP_USER_AGENT']. $_SERVERis a special reserved PHP variable that contains all web server information. It is known as a superglobal <?phpecho$_SERVER['HTTP_USER_AGENT']; ?> EXAMPLE now you must be thinking what is $_SERVER? www.facebook.com/VineetOO7
  • 8. LANGUAGEBASIC •PHP tags •Instruction separation •Comments PHP tags When PHP parses a file, it looks for opening and closing tags, which are<?phpand?>which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. PHP also allows for short tags<?and?>(which are discouraged because they are only available if enabled withshort_open_tagphp.iniconfiguration file directive, or if PHP was configured with the--enable-short-tags option. If a file is pure PHP code, it is preferable omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines after PHP closing tag which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script. www.facebook.com/VineetOO7
  • 9. LANGUAGEBASIC 2.<scriptlanguage="php"> echo„is it good to write code like this...? No idon't think so.'; </script> 3.<?echo„this is short php tag to use echoing (print ) ';?> 4.<?=”it‟s pretty good ! But this looks like Java Server Page‟s expression tag...”?> 1.<?phpecho'this is php ,doyou likethis ?';?> one and two are both always available, example one is the most commonly used, and recommended, of the two. Short tags (example three) are only available when they are enabled via theshort_open_tagphp.iniconfiguration file directive, or if PHP was configured with the--enable-short-tagsoption. ASPstyle tags (example four) are only available when they are enabled via theasp_tagsphp.iniconfiguration file directive. www.facebook.com/VineetOO7
  • 10. •<?phpecho'Thisisatest'; ?> •<?echo'Thisisatest'?> •<?phpecho'Weomittedthelastclosingtag'; Instruction separation As in C or Perl, PHP requires and other programming language instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present. LANGUAGEBASIC The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when usinginclude()orrequire(). Include() or require() we‟ll discuss a bit later in this session www.facebook.com/VineetOO7
  • 11. Comments LANGUAGEBASIC PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example: <?phpecho‟good morning Alpana..';//Thisisaone-linec++stylecomment/*Thisisamultilinecommentyetanotherlineofcomment*/ echo”Thisisyetanothertest”; echo'OneFinalTest';#Thisisaone-lineshell-stylecomment?> www.facebook.com/VineetOO7
  • 12. Types LANGUAGEBASIC PHP supports these primitive types boolean integer Float string array object resource NULL Some examples: To forcibly convert a variable to a certain type, eithercastthe variable or use thesettype()function on it. <?php$a_bool=TRUE;//aboolean$a_str="foo";//astring$a_str2='foo';//astring$an_int=12;//anintegerechogettype($a_bool);//printsout:booleanechogettype($a_str);//printsout:string//Ifthisisaninteger,incrementitbyfourif(is_int($an_int)){ $an_int+=4; } //If$a_boolisastring,printitout//(doesnotprintoutanything) if(is_string($a_bool)){ echo"String:$a_bool"; } ?> Two compound types: special types: Four scalar types: Php supports some more pseudo type like mixed , number , callbackbut for the time being the these are sufficient www.facebook.com/VineetOO7
  • 13. void voidas a return type means that the return value is useless.voidin a parameter list means that the function doesn't accept any parameters. mixed mixedindicates that a parameter may accept multiple (but not necessarily all) types. gettype()for example will accept all PHP types, number numberindicates that a parameter can be eitherintegerorfloat. ... $...in function prototypes meansand so on. This variable name is used when a function can take an endless number of arguments. LANGUAGEBASIC www.facebook.com/VineetOO7
  • 14. LANGUAGEBASIC Abooleanexpresses a truth value. It can be eitherTRUEorFALSE. Booleans This is the simplest type. To specify abooleanliteral, use the keywordsTRUEorFALSE. Both are case-insensitive. Typically, the result of anoperatorwhich returns abooleanvalue is passed on to acontrol structure. <?php$foo=True;//assignthevalueTRUEto$foo?> <?php//==isanoperatorwhichtests//equalityandreturnsabooleanif($action=="show_version"){ echo"Theversionis1.23"; } //thisisnotnecessary... if($show_separators==TRUE){ echo"<hr>n"; } //...becausethiscanbeusedwithexactlythesamemeaning: if($show_separators){ echo"<hr>n"; } ?> www.facebook.com/VineetOO7
  • 15. Converting to boolean LANGUAGEBASIC To explicitly convert a value toboolean, use the(bool)or(boolean)casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires abooleanargument. When converting toboolean, the following values are consideredFALSE: •thebooleanFALSEitself •theinteger0 (zero) •thefloat0.0 (zero) •the emptystring, and thestring"0" •anarraywith zero elements •anobjectwith zero member variables (PHP 4 only) •the special typeNULL(including unset variables) •SimpleXMLobjects created from empty tags Every other value is consideredTRUE <?phpvar_dump((bool)"");//bool(false) var_dump((bool)1);//bool(true) var_dump((bool)-2);//bool(true) var_dump((bool)"foo");//bool(true) var_dump((bool)2.3e5);//bool(true) var_dump((bool)array(12));//bool(true) var_dump((bool)array());//bool(false) var_dump((bool)"false");//bool(true) ?> www.facebook.com/VineetOO7
  • 16. Integers Anintegeris a number of the set ℤ= {..., -2, -1, 0, 1, 2, ...}. Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (-or +). To use octal notation, precede the number with a0(zero). To use hexadecimal notation precede the number with0x. Example #1 Integer literals <?php$a=1234;//decimalnumber$a=-123;//anegativenumber$a=0123;//octalnumber(equivalentto83decimal) $a=0x1A;//hexadecimalnumber(equivalentto26decimal) ?> The size of anintegeris platform-dependent, Converting to integer To explicitly convert a value tointeger, use either the(int)or(integer)casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires anintegerargument. A value can also be converted tointegerwith theintval()function. www.facebook.com/VineetOO7
  • 17. Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes: <?php$a=1.234; $b=1.2e3; $c=7E-10; ?> Comparing floats As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations. To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations. $aand$bare equal to 5 digits of precision. Formally: LNUM [0-9]+ DNUM ([0-9]*[.]{LNUM}) | ({LNUM}[.][0-9]*) EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM}) exp. <?php$a=1.23456789; $b=1.23456780; $epsilon=0.00001; if(abs($a- $b)<$epsilon){ echo"true"; } ?> Floating point numbers www.facebook.com/VineetOO7
  • 18. Strings Astringis series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. Note:It is no problem for astringto become very large. PHP imposes no boundary on the size of astring; the only limit is the available memory of the computer on which PHP is running. Astringliteral can be specified in four different ways: single quoted double quoted heredocsyntax nowdocsyntax(since PHP 5.3.0) Single quoted The simplest way to specify astringis to enclose it in single quotes To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (). <?phpecho'thisisasimple single quotedstring'; www.facebook.com/VineetOO7
  • 19. Double quoted If thestringis enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters: n, r, t Heredoc A third way to delimitstrings is the heredocsyntax:<<<. After this operator, an identifier is provided, then a newline. Thestringitself follows, and then the same identifier again to close the quotation. The closing identifiermustbegin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. It is very important to note that the line with the closing identifier must contain no other characters, exceptpossiblya semicolon (;). That means especially that the identifiermay not be indented, and there may not be any spaces or tabs before or after the semicolon. Strings www.facebook.com/VineetOO7
  • 20. example <?php$str=<<<EODExampleofstringspanningmultiplelinesusingheredocsyntax. EOD; /*Morecomplexexample,withvariables.*/ classfoo{ var$foo; var$bar; functionfoo() { $this->foo='Foo'; $this->bar=array('Bar1','Bar2','Bar3'); } } $foo=newfoo(); $name='MyName'; echo<<<EOTMynameis"$name".Iamprintingsome$foo->foo. Now,Iamprintingsome{$foo->bar[1]}. Thisshouldprintacapital'A':x41EOT; ?> Strings www.facebook.com/VineetOO7
  • 21. Anarrayin PHP is actually an ordered map. A map is a type that associatesvaluestokeys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. Asarrayvalues can be otherarrays, trees and multidimensionalarrays are also possible. Explanation of those data structures is beyond the scope of this manual, but at least some example is provided Anarraycan be created using thearray()language construct. It takes any number of comma- separatedkey=>valuepairs as arguments. array( key => value, key2 => value2, key3 => value3, ... ) <?php$array=array( "foo"=>"bar", "bar"=>"foo", ); //asofPHP5.4$array=[ "foo"=>"bar", "bar"=>"foo", ]; ?> Arrays www.facebook.com/VineetOO7
  • 22. Additionally the followingkeycasts will occur: Strings containing validintegers will be cast to theintegertype. E.g. the key"8"will actually be stored under8. On the other hand"08"will not be cast, as it isn't a valid decimal integer. Floats are also cast tointegers, which means that the fractional part will be truncated. E.g. the key8.7will actually be stored under8. Boolsare cast tointegers, too, i.e. the keytruewill actually be stored under1and the keyfalseunder0. Nullwill be cast to the empty string, i.e. the keynullwill actually be stored under"". Arrays andobjectscan notbe used as keys. Doing so will result in a warning:Illegal offset type. <?php$array=array( 1=>"a", "1"=>"b", 1.5=>"c", true=>"d", ); var_dump($array); ?> Array www.facebook.com/VineetOO7
  • 23. <?phpclassfoo{ functiondo_foo() { echo"Doingfoo."; } } $bar=newfoo; $bar->do_foo(); ?> Objects To create a newobject, use thenewstatement to instantiate a class: Object Initialization For more we‟ll be back very sooooooon....... www.facebook.com/VineetOO7
  • 24. Resources Aresourceis a special variable, holding a reference to an external resource. Resources are created and used by special functions. NULL The specialNULLvalue represents a variable with no value.NULLis the only possible value of typeNULL. A variable is considered to benullif: •it has been assigned the constantNULL. •it has not been set to any value yet. •it has beenunset(). There is only one value of typenull, and that is the case-insensitive constantNULL. <?php$var=NULL; ?> www.facebook.com/VineetOO7
  • 25. PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if astringvalue is assigned to variable$var,$varbecomesastring. If anintegervalue is then assigned to$var, it becomes aninteger. <?php$foo="0";//$fooisstring(ASCII48) $foo+=2;//$fooisnowaninteger(2) $foo=$foo+1.3;//$fooisnowafloat(3.3) $foo=5+"10LittlePiggies";//$fooisinteger(15) $foo=5+"10SmallPigs";//$fooisinteger(15) ?> Type Juggling www.facebook.com/VineetOO7
  • 26. The casts allowed are: •(int), (integer) -cast tointeger •(bool), (boolean) -cast toboolean •(float), (double), (real) -cast tofloat •(string) -cast tostring •(array) -cast toarray •(object) -cast toobject •(unset) -cast toNULL(PHP 5) <?php$foo=10;//$fooisaninteger$bar=(boolean)$foo;//$barisaboolean?> Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. Type Casting www.facebook.com/VineetOO7
  • 27. Variables Basics Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. <?php$var='Bob'; $Var='Joe'; echo"$var,$Var";//outputs"Bob,Joe" $4site='notyet';//invalid;startswithanumber$_4site='notyet';//valid;startswithanunderscore$täyte='mansikka';//valid;'ä'is(Extended)ASCII228. ?> www.facebook.com/VineetOO7
  • 28. To assign by reference, simply prependan ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice: <?php$foo='Bob';//Assignthevalue'Bob'to$foo$bar=&$foo;//Reference$foovia$bar. $bar="Mynameis$bar";//Alter$bar... echo$bar; echo$foo;//$fooisalteredtoo. ?> Variables www.facebook.com/VineetOO7
  • 29. PHP provides a large number of predefined variables to any script which it runs. Variable scope <?php$a=1;/*globalscope*/ functiontest() { echo$a;/*referencetolocalscopevariable*/ } test(); ?> Usingglobal <?php$a=1; $b=2; functionSum() { global$a,$b; $b=$a+$b; } Sum(); echo$b; // 3?> Predefined Variables www.facebook.com/VineetOO7
  • 30. Using$GLOBALSinstead of global <?php$a=1; $b=2; functionSum() { $GLOBALS['b']=$GLOBALS['a']+$GLOBALS['b']; } Sum(); echo$b; ?> www.facebook.com/VineetOO7
  • 31. The$GLOBALSarray is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how$GLOBALSexists in any scope, this is because$GLOBALSis asuperglobal. Example demonstrating superglobalsand scope <?phpfunctiontest_global() { //Mostpredefinedvariablesaren't"super"andrequire//'global'tobeavailabletothefunctionslocalscope. global$HTTP_POST_VARS; echo$HTTP_POST_VARS['name']; //Superglobalsareavailableinanyscopeanddo//notrequire'global'.Superglobalsareavailable//asofPHP4.1.0,andHTTP_POST_VARSisnow//deemeddeprecated. echo$_POST['name']; } ?> www.facebook.com/VineetOO7
  • 32. Another important feature of variable scoping is thestaticvariable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example: <?phpfunctiontest() { $a=0; echo$a; $a++; } ?> Now,$ais initialized only in first call of function and every time thetest()function is called it will print the value of$aand increment it. <?phpfunctiontest() { static$a=0; echo$a; $a++; } ?> This function is quite useless since every time it is called it sets$ato0and prints0. The$a++ which increments the variable serves no purpose since as soon as the function exits the$avariable disappears Usingstaticvariables www.facebook.com/VineetOO7
  • 33. Declaring static variables <?phpfunctionfoo(){ static$int=0;//correctstatic$int=1+2;//wrong(asitisanexpression) static$int=sqrt(121);//wrong(asitisanexpressiontoo) $int++; echo$int; } ?> Note: Static declarations are resolved in compile-time. www.facebook.com/VineetOO7
  • 34. <?php$$a='world'; ?> Sometimes it is convenient to be able to have variable variablenames. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as: A variable variabletakes the value of a variable and treats that as the name of a variable. In the above example,hello, can be used as the name of a variable by using two dollar signs. i.e. At this point two variables have been defined and stored in the PHP symbol tree:$awith contents "hello" and$hellowith contents "world". Therefore, this statement: <?php$a='hello'; ?> <?phpecho"$a${$a}"; ?> produces the exact same output ,they both produce:hello world. <?phpecho"$a$hello"; ?> Variable variables www.facebook.com/VineetOO7
  • 35. Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as$foo->$bar, then the local scope will be examined for$barand its value will be used as the name of the property of$foo. This is also true if$baris an array access. The above example will output: I am bar. I am bar. <?phpclassfoo{ var$bar='Iambar.'; } $foo=newfoo(); $bar='bar'; $baz=array('foo','bar','baz','quux'); echo$foo->$bar."n"; echo$foo->$baz[1]."n"; ?> Example: Variable property example www.facebook.com/VineetOO7
  • 36. Variables From External Sources HTML Forms (GET and POST) When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example: <form action="foo.php" method="post"> Name: <input type="text" name="username" /><br/> Email: <input type="text" name="email" /><br/> <input type="submit" name="submit" value="Submit me!" /> </form> <?phpecho$_POST['username']; echo$_REQUEST['username']; import_request_variables('p','p_'); echo$p_username; echo$HTTP_POST_VARS['username']; echo$username; ?> www.facebook.com/VineetOO7
  • 37. Constants A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except formagic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. Valid and invalid constant names <?php//Validconstantnamesdefine("FOO","something"); define("FOO2","somethingelse"); define("FOO_BAR","somethingmore"); //Invalidconstantnamesdefine("2FOO","something"); //Thisisvalid,butshouldbeavoided: //PHPmayonedayprovideamagicalconstant//thatwillbreakyourscriptdefine("__FOO__","something"); ?> Defining Constants using theconstkeyword <?php//WorksasofPHP5.3.0constCONSTANT='HelloWorld'; echoCONSTANT; ?> www.facebook.com/VineetOO7
  • 38. Operators An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value www.facebook.com/VineetOO7
  • 39. Control Structures •if •else •elseif/else if •while •do-while •for •foreach •break •continue •switch •Return •Include •include_once Skip the content... www.facebook.com/VineetOO7
  • 40. Functions User-defined functions Function arguments Returning values Variable functions(skiped) Internal (built-in) functions Anonymous functions Pseudo code to demonstrate function uses <?phpfunctionfoo($arg_1,$arg_2,/*...,*/$arg_n) { echo"Examplefunction.n"; return$retval; } ?> User-defined functions A function may be defined using syntax such as the following: www.facebook.com/VineetOO7
  • 41. Conditional functions <?php$makefoo=true; /*Wecan'tcallfoo()fromhere sinceitdoesn'texistyet, butwecancallbar()*/ bar(); if($makefoo){ functionfoo() { echo"Idon'texistuntilprogram executionreachesme.n"; } } /*Nowwecansafelycallfoo() since$makefooevaluatedtotrue*/ if($makefoo)foo(); functionbar() { echo"Iexistimmediatelyuponprogramstart.n"; } ?> www.facebook.com/VineetOO7
  • 42. Functions within functions <?phpfunctionfoo() { functionbar() { echo"Idon'texistuntilfoo()iscalled.n"; } } /*Wecan'tcallbar()yetsinceitdoesn'texist.*/ foo(); /*Nowwecancallbar(), foo()'sprocessinghasmadeitaccessible.*/ bar(); ?> All functions and classes in PHP have the global scope -they can be called outside a function even if they were defined inside and vice versa. PHP does not support function overloading, nor is it possible to undefineor redefine previously-declared functions. Note:Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration. www.facebook.com/VineetOO7
  • 43. information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right. Function arguments PHP supports passing arguments by value (the default),passing by reference, anddefault argument values.Variable-length argument listsare also supported, Passing arrays to functions <?phpfunctiontakes_array($input) { echo"$input[0]+$input[1]=",$input[0]+$input[1]; } ?> Passing function parameters by reference <?phpfunctionadd_some_extra(&$string) { $string.='andsomethingextra.'; } $str='Thisisastring,'; add_some_extra($str); echo$str;//outputs'Thisisastring,andsomethingextra.' ?> www.facebook.com/VineetOO7
  • 44. Use of default parameters in functions Default argument values A function may define C++-style default values for scalar arguments as follows: <?phpfunctionmakecoffee($type="cappuccino") { return"Makingacupof$type.n"; } echomakecoffee(); echomakecoffee(null); echomakecoffee("espresso"); ?> The above example will output: Making a cup of cappuccino. Making a cup of . Making a cup of espresso. www.facebook.com/VineetOO7
  • 45. PHP has support for variable-length argument lists in user-defined functions. This is really quite easy, using thefunc_num_args(),func_get_arg(), andfunc_get_args()functions. func_num_args—Returns the number of arguments passed to the function func_num_args()example <?phpfunctionfoo() { $numargs=func_num_args(); echo"Numberofarguments:$numargsn"; } foo(1,2,3);// 3?> Number of arguments: 3 Variable-length argument lists No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal. www.facebook.com/VineetOO7
  • 46. func_get_arg—Return an item from the argument list func_get_arg()example <?phpfunctionfoo() { $numargs=func_num_args(); echo"Numberofarguments:$numargs<br/>n"; if($numargs>=2){ echo"Secondargumentis:".func_get_arg(1)."<br/>n"; } } foo(1,2,3); ?> func_get_args—Returns an array comprising a function's argument list <?phpfunctionfoo() { $numargs=func_num_args(); echo"Numberofarguments:$numargs<br/ >n"; if($numargs>=2){ echo"Secondargumentis:".func_get_arg(1)."<br/>n"; } $arg_list=func_get_args(); for($i=0;$i<$numargs;$i++){ echo"Argument$iis:".$arg_list[$i]."<br/>n"; } } foo(1,2,3); ?> www.facebook.com/VineetOO7
  • 47. Variable functions PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. Variable function example <?phpfunctionfoo(){ echo"Infoo()<br/>n"; } functionbar($arg=„ „) { echo"Inbar();argumentwas'$arg'.<br/> n"; } //Thisisawrapperfunctionaroundechofunctionechoit($string) { echo$string; } $func='foo'; $func();//Thiscallsfoo() $func='bar'; $func('test');//Thiscallsbar() $func='echoit'; $func('test');//Thiscallsechoit() ?> www.facebook.com/VineetOO7
  • 48. Anonymous functions Anonymous functions, also known asclosures, allow the creation of functions which have no specified name. They are most useful as the value ofcallbackparameters, but they have many other uses. Anonymous function variable assignment example <?php$greet=function($name) { printf("Hello%srn",$name); }; $greet('World'); $greet('PHP'); ?> www.facebook.com/VineetOO7
  • 49. OBJECT-ORIENTED-PROGRAMMING Object: Repository of data. Milk Jam Honey Bread Biscuits myList myList is an object of classShoppingList Terminology Class: Type of object ShoppingList ShoppingCart For different types of objects the methodsof putting milk in them vary. Method: Procedure or function that operates on an object or on a class of objects. Milk Jam myList addItem(Honey) myList myShoppingCart www.facebook.com/VineetOO7
  • 50. OBJECT-ORIENTED-PROGRAMMING Terminology Polymorphism: One method call can work on several different classes of objects, even if the classes need different implementations e.g. “addItem” method on every kind of List, even though adding item to ShoppingList is very different from adding milk to ShoppingCart. This is done using dynamic method Object Oriented: Each object knows its class and knows which methods work on that class. Each ShoppingList and ShoppingCart knows which “addItem” method it should use. Inheritance: A class can inherit properties from a more general class. ShoppingList inherits from List class the property of storing a sequence of items. www.facebook.com/VineetOO7
  • 51. class Basic class definitions begin with the keywordclass, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label which is a not a PHPreserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. A class may contain its ownconstants,variables(called "properties"), and functions (called "methods"). Simple Class definition <?phpclassSimpleClass{ //propertydeclarationpublic$var='adefaultvalue„; //methoddeclarationpublicfunctiondisplayVar(){ echo$this->var; } } ?> www.facebook.com/VineetOO7 The Basics
  • 52. To create an instance of a class, thenewkeyword must be used. An object will always be created unless the object has aconstructordefined that throws anexceptionon error. Classes should be defined before instantiation (and in some cases this is a requirement). <?php$instance=newSimpleClass(); Object Assignment <?php$instance=newSimpleClass(); $assigned=$instance; $reference=&$instance; $instance->var='$assignedwillhavethisvalue'; $instance=null;//$instanceand$referencebecomenullvar_dump($instance); var_dump($reference); var_dump($assigned); ?> www.facebook.com/VineetOO7 new
  • 53. The inherited methods and properties can be overridden by redeclaringthem with the same name defined in the parent class. However, if the parent class has defined a method asfinal, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them withparent::. When overriding methods, the parameter signature should remain the same Simple Class Inheritance <?phpclassExtendClassextendsSimpleClass{ //RedefinetheparentmethodfunctiondisplayVar() { echo"Extendingclassn"; parent::displayVar(); } } $extended=newExtendClass(); $extended->displayVar(); ?> www.facebook.com/VineetOO7 extends A class can inherit the methods and properties of another class by using the keywordextendsin the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.
  • 54. Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywordspublic,protected, orprivate, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated property declarations <?phpclassSimpleClass{ //invalidpropertydeclarations: public$var1='hello'.'world'; public$var2=<<<EODhelloworldEOD; public$var3=1+2; public$var4=self::myStaticMethod( ); public$var5=$myVar; //validpropertydeclarations: public$var6=myConstant; public$var7=array(true,false); //ThisisallowedonlyinPHP5.3.0andlater. public$var8=<<<'EOD'helloworldEOD; } ?> www.facebook.com/VineetOO7 Properties
  • 55. It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the$symbol to declare or use them. The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call. Defining and using a constant <?phpclassMyClass{ constconstant='constantvalue'; functionshowConstant(){ echoself::constant."n"; } } echoMyClass::constant."n"; $classname="MyClass"; echo$classname::constant."n";//AsofPHP5.3.0$class=newMyClass(); $class->showConstant(); echo$class::constant."n";//AsofPHP5.3.0?> www.facebook.com/VineetOO7 Class Constants
  • 56. Constructors and Destructors void__construct([mixed$args[,$...]] ) PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. Note:Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call toparent::__construct()within the child constructor is required. Constructor Its slightly differ from java or other Object Oriented programming language.. using new unified constructors <?phpclassBaseClass{ function__construct(){ print"InBaseClassconstructorn"; } } classSubClassextendsBaseClass{ function__construct(){ parent::__construct(); print"InSubClassconstructorn"; } } $obj=newBaseClass(); $obj=newSubClass(); ?> www.facebook.com/VineetOO7
  • 57. Constructors in namespacedclasses <?phpnamespaceFoo; classBar{ publicfunctionBar(){ //treatedasconstructorinPHP5.3.0-5.3.2//treatedasregularmethodasofPHP5.3.3} } ?> www.facebook.com/VineetOO7
  • 58. Destructor Example Destructor void__destruct(void) PHP 5 introduces a destructor concept similar to that of other object- oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly callparent::__destruct()in the destructor body. The destructor will be called even if script execution is stopped usingexit(). Callingexit()in a destructor will prevent the remaining shutdown routines from executing. www.facebook.com/VineetOO7 <?phpclassMyDestructableClass{ function__construct(){ print"Inconstructorn"; $this->name="MyDestructableClass"; } function__destruct(){ print"Destroying".$this->name."n"; } } $obj=newMyDestructableClass(); ?>
  • 59. Property declaration /** *DefineMyClass2*/ classMyClass2extendsMyClass{ //Wecanredeclarethepublicandprotectedmethod,butnotprivateprotected$protected='Protected2'; functionprintHello() { echo$this->public; echo$this->protected; echo$this->private; } } $obj2=newMyClass2(); echo$obj2->public;//Worksecho$obj2->private;//Undefinedecho$obj2->protected;//FatalError$obj2->printHello(); //ShowsPublic,Protected2,Undefined?> <?php/** *DefineMyClass*/ classMyClass{ public$public='Public'; var$default = „public‟; protected$protected='Protected'; private$private='Private'; functionprintHello() { echo$this->public; echo$this->protected; echo$this->private; } } $obj=newMyClass(); echo$obj->public;//Worksecho$obj->protected;//FatalErrorecho$obj->private;//FatalError$obj->printHello(); //ShowsPublic,ProtectedandPrivate www.facebook.com/VineetOO7
  • 60. Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public. <?phpclassMyClass{ //Declareapublicconstructorpublicfunction__construct(){} //DeclareapublicmethodpublicfunctionMyPublic(){} //DeclareaprotectedmethodprotectedfunctionMyProtected(){} //DeclareaprivatemethodprivatefunctionMyPrivate(){} //ThisispublicfunctionFoo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } } $myclass=newMyClass; $myclass->MyPublic();//Works$myclass->MyProtected();//FatalError$myclass->MyPrivate();//FatalError$myclass->Foo();//Public,ProtectedandPrivatework /** *DefineMyClass2*/ classMyClass2extendsMyClass{ //ThisispublicfunctionFoo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate();//FatalError} } $myclass2=newMyClass2; $myclass2->MyPublic();//Works$myclass2- >Foo2();//PublicandProtectedwork,notPrivate www.facebook.com/VineetOO7 Method Visibility Method Declaration
  • 61. Object Inheritance Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another. when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality. Inheritance Example <?phpclassfoo{ publicfunctionprintItem($string) { echo'Foo:'.$string.PHP_EOL; } publicfunctionprintPHP() { echo'PHPisgreat.'.PHP_EOL; } } classbarextendsfoo{ publicfunctionprintItem($string) { echo'Bar:'.$string.PHP_EOL; } } $foo=newfoo(); $bar=newbar(); $foo->printItem('baz');//Output:'Foo:baz' $foo->printPHP();//Output:'PHPisgreat' $bar->printItem('baz');//Output:'Bar:baz' $bar->printPHP();//Output:'PHPisgreat' ?> www.facebook.com/VineetOO7
  • 62. Scope Resolution Operator (::) ::from outside the class definition <?phpclassMyClass{ constCONST_VALUE='Aconstantvalue'; } $classname='MyClass'; echo$classname::CONST_VALUE;//AsofPHP5.3.0echoMyClass::CONST_VALUE; ?> :: from inside the class definition <?phpclassOtherClassextendsMyClass{ publicstatic$my_static='staticvar'; publicstaticfunctiondoubleColon(){ echoparent::CONST_VALUE."n"; echoself::$my_static."n"; } } $classname='OtherClass'; echo$classname::doubleColon();//AsofPHP5.3.0OtherClass::doubleColon(); ?> www.facebook.com/VineetOO7
  • 63. Calling a parent's method <?phpclassMyClass{ protectedfunctionmyFunc(){ echo"MyClass::myFunc()n"; } } classOtherClassextendsMyClass{ //Overrideparent'sdefinitionpublicfunctionmyFunc() { //Butstillcalltheparentfunctionparent::myFunc(); echo"OtherClass::myFunc()n"; } } $class=newOtherClass(); $class->myFunc(); ?> www.facebook.com/VineetOO7
  • 64. Static Keyword Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can). if novisibilitydeclaration is used, then the property or method will be treated as if it was declared aspublic. Static properties cannot be accessed through the object using the arrow operator ->. Calling non-static methods statically generates anE_STRICTlevel warning. Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object. Static property example <?phpclassFoo{ publicstatic$my_static='foo'; publicfunctionstaticValue(){ returnself::$my_static; } } classBarextendsFoo{ publicfunctionfooStatic(){ returnparent::$my_static; } } printFoo::$my_static."n"; $foo=newFoo(); print$foo->staticValue()."n"; print$foo->my_static."n";//Undefined"Property"my_staticprint$foo::$my_static."n"; $classname='Foo'; print$classname::$my_static."n";//AsofPHP5.3.0printBar::$my_static."n"; $bar=newBar(); print$bar->fooStatic()."n"; ?> www.facebook.com/VineetOO7
  • 65. Class Abstraction PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature -they cannot define the implementation. <?phpabstractclassAbstractClass{ //ForceExtendingclasstodefinethismethodabstractprotectedfunctiongetValue(); abstractprotectedfunctionprefixValue($prefix); //CommonmethodpublicfunctionprintOut(){ print$this->getValue()."n"; } } classConcreteClass1extendsAbstractClass{ protectedfunctiongetValue(){ return"ConcreteClass1"; } publicfunctionprefixValue($prefix){ return"{$prefix}ConcreteClass1“;} } classConcreteClass2extendsAbstractClass{ publicfunctiongetValue(){ return"ConcreteClass2"; } publicfunctionprefixValue($prefix){ return"{$prefix}ConcreteClass2"; } } $class1=newConcreteClass1; $class1->printOut(); echo$class1->prefixValue('FOO_')."n"; $class2=newConcreteClass2; $class2->printOut(); echo$class2->prefixValue('FOO_')."n"; ?> ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2 www.facebook.com/VineetOO7
  • 66. Object Interfaces Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined. All methods declared in an interface must be public, this is the nature of an interface. implements To implement an interface, theimplementsoperator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma. Interfaces can be extended like classes using theextendsoperator. The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error. Constants Its possible for interfaces to have constants. Interface constants works exactly likeclass constantsexcept they cannot be overridden by a class/interface that inherits it. www.facebook.com/VineetOO7
  • 67. Interface example <?php//Declaretheinterface'iTemplate'interfaceiTemplate{ publicfunctionsetVariable($name,$var); publicfunctiongetHtml($template); } //Implementtheinterface//ThiswillworkclassTemplateimplementsiTemplate{ private$vars=array(); publicfunctionsetVariable($name,$var) { $this->vars[$name]=$var; } publicfunctiongetHtml($template) { foreach($this->varsas$name=>$value){ $template=str_replace('{'.$name.'}',$value, $template); } return$template; } } //Thiswillnotwork//Fatalerror:ClassBadTemplatecontains1abstractmethods//andmustthereforebedeclaredabstract(iTemplate:: getHtml) classBadTemplateimplementsiTemplate{ private$vars=array(); publicfunctionsetVariable($name,$var) { $this->vars[$name]=$var; } } ?> www.facebook.com/VineetOO7
  • 68. Extendable Interfaces <?phpinterfacea{ publicfunctionfoo(); } interfacebextendsa{ publicfunctionbaz(Baz$baz); } //Thiswillworkclasscimplementsb{ publicfunctionfoo() { } publicfunctionbaz(Baz$baz) { } } //Thiswillnotworkandresultinafatalerrorclassdimplementsb{ publicfunctionfoo() { } publicfunctionbaz(Foo$foo) { } } ?> www.facebook.com/VineetOO7
  • 69. Multiple interface inheritance <?phpinterfacea{ publicfunctionfoo(); } interfaceb{ publicfunctionbar(); } interfacecextendsa,b{ publicfunctionbaz(); } classdimplementsc{ publicfunctionfoo() { } publicfunctionbar() { } publicfunctionbaz() { } } ?> www.facebook.com/VineetOO7
  • 70. Interfaces with constants <?phpinterfacea{ constb='Interfaceconstant'; } //Prints:Interfaceconstantechoa::b; //Thiswillhowevernotworkbecauseitsnotallowedto//overrideconstants. classbimplementsa{ constb='Classconstant'; } ?> www.facebook.com/VineetOO7
  • 71. Overloading Overloading in PHP provides means to dynamically "create" properties and methods. All overloading methods must be defined aspublic. <?phpclassPropertyTest{ /**Locationforoverloadeddata.*/ private$data=array(); /**Overloadingnotusedondeclaredproperties.*/ public$declared=1; /**Overloadingonlyusedonthiswhenaccessedoutsidetheclass. */ private$hidden=2; publicfunction__set($name,$value) { echo"Setting'$name'to'$value'n"; $this->data[$name]=$value; } publicfunction__get($name) { echo"Getting'$name'n"; if(array_key_exists($name, $this->data)){ return$this- >data[$name]; } $trace=debug_backtrace(); trigger_error( 'Undefinedpropertyvia__get():'.$name. 'in'.$trace[0]['file']. 'online'.$trace[0][ 'line'], E_USER_NOTICE); returnnull; } www.facebook.com/VineetOO7
  • 72. /**AsofPHP5.1.0*/ publicfunction__isset($name) { echo"Is'$name'set?n"; returnisset($this- >data[$name]); } /**AsofPHP5.1.0*/ publicfunction__unset($name) { echo"Unsetting'$name'n"; unset($this->data[$name]); } /**Notamagicmethod,justhereforexample.*/ publicfunctiongetHidden() { return$this->hidden; } } echo"<pre>n"; $obj=newPropertyTest; $obj->a=1; echo$obj->a."nn"; var_dump(isset($obj->a)); unset($obj->a); var_dump(isset($obj->a)); echo"n"; echo$obj->declared."nn"; echo"Let'sexperimentwiththeprivatepropertynamed'hidden':n"; echo"Privatesarevisibleinsidetheclass,so__get()notused...n" ; echo$obj->getHidden()."n"; echo"Privatesnotvisibleoutsideofclass,so__get()isused...n"; echo$obj->hidden."n"; ?> www.facebook.com/VineetOO7
  • 73. Method overloading publicmixed__call(string$name,array$arguments) public staticmixed__callStatic(string$name,array$arguments) __call()is triggered when invoking inaccessible methods in an object context. __callStatic()is triggered when invoking inaccessible methods in a static context. The$nameargument is the name of the method being called. The$argumentsargument is an enumerated array containing the parameters passed to the$name'edmethod. Overloading methods via the__call()and__callStatic()methods <?phpclassMethodTest{ publicfunction__call($name,$arguments) { //Note:valueof$nameiscasesensitive. echo"Callingobjectmethod'$name'" .implode(',',$arguments)."n"; } /**AsofPHP5.3.0*/ publicstaticfunction__callStatic($name,$arguments) { //Note:valueof$nameiscasesensitive. echo"Callingstaticmethod'$name'" .implode(',',$arguments)."n"; } } $obj=newMethodTest; $obj->runTest('inobjectcontext'); MethodTest::runTest('instaticcontext');//AsofPHP5.3.0?> The above example will output: Calling object method 'runTest' in object context Calling static method 'runTest' in static context www.facebook.com/VineetOO7
  • 74. Object Iteration PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example aforeachstatement. By default, allvisibleproperties will be used for the iteration <?phpclassMyClass{ public$var1='value1'; public$var2='value2'; public$var3='value3'; protected$protected='protectedvar'; private$private='privatevar'; functioniterateVisible(){ echo"MyClass::iterateVisible:n"; foreach($thisas$key=>$value) { print"$key=>$valuen"; } } } $class=newMyClass(); foreach($classas$key=>$value){ print"$key=>$valuen"; } echo"n"; $class->iterateVisible(); ?> The above example will output: var1 => value 1 var2 => value 2 var3 => value 3 MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected varprivate => private var www.facebook.com/VineetOO7
  • 75. Object Iteration implementing Iterator <?phpclassMyIteratorimplementsIterator{ private$var=array(); publicfunction__construct($array) { if(is_array($array)){ $this->var=$array; } } publicfunctionrewind() { echo"rewindingn"; reset($this->var); } publicfunctioncurrent() { $var=current($this->var); echo"current:$varn"; return$var; } publicfunctionkey() { $var=key($this->var); echo"key:$varn"; return$var; } publicfunctionnext() { $var=next($this->var); echo"next:$varn"; return$var; } publicfunctionvalid() { $key=key($this->var); $var=($key!==NULL&&$key!== FALSE); echo"valid:$varn"; return$var; } } $values=array(1,2,3); $it=newMyIterator($values); foreach($itas$a=>$b) { print"$a:$bn"; } ?> rewinding valid: 1 current: 1 key: 0 0: 1 next: 2 valid: 1 current: 2 key: 1 1: 2 next: 3 valid: 1 current: 3 key: 2 2: 3 next: valid: www.facebook.com/VineetOO7
  • 76. Final Keyword PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. Final methods example <?phpclassBaseClass{ publicfunctiontest(){ echo"BaseClass::test()calledn"; } finalpublicfunctionmoreTesting(){ echo"BaseClass::moreTesting()calledn"; } } classChildClassextendsBaseClass{ publicfunctionmoreTesting(){ echo"ChildClass::moreTesting()calledn"; } } //ResultsinFatalerror:CannotoverridefinalmethodBaseClass::moreTesting() ?> Final class example <?phpfinalclassBaseClass{ publicfunctiontest(){ echo"BaseClass::test()calledn"; } //Hereitdoesn'tmatterifyouspecifythefunctionasfinalornotfinalpublicfunctionmoreTesting(){ echo"BaseClass::moreTesting()calledn"; } } classChildClassextendsBaseClass{ } //ResultsinFatalerror:ClassChildClassmaynotinheritfromfinalclass(BaseClass) ?> www.facebook.com/VineetOO7
  • 77. Object Cloning Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, An object copy is created by using the clone keyword (which calls the object's__clone()method if possible). An object's__clone()method cannot be called directly. $copy_of_object= clone $object; When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. <?phpclassSubObject{ static$instances=0; public$instance; publicfunction__construct(){ $this->instance=++self::$instances; } publicfunction__clone(){ $this->instance=++self::$instances; } } classMyCloneable{ public$object1; public$object2; function__clone() { //Forceacopyofthis->object,otherwise//itwillpointtosameobject. $this->object1=clone$this->object1; } } $obj=newMyCloneable(); $obj->object1= newSubObject(); $obj->object2= newSubObject(); $obj2=clone$obj; print("OriginalObject:n"); print_r($obj); print("ClonedObject:n"); print_r($obj2); ?> Original Object: MyCloneableObject ( [object1] => SubObjectObject ( [instance] => 1 ) [object2] => SubObjectObject ( [instance] => 2 ) ) Cloned Object: MyCloneableObject ( [object1] => SubObjectObject ( [instance] => 3 ) [object2] => SubObjectObject ( [instance] => 2 ) ) www.facebook.com/VineetOO7
  • 78. Comparing Objects In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language). When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class. <?phpfunctionbool2str($bool) { if($bool===false){ return'FALSE'; }else{ return'TRUE'; } } functioncompareObjects(&$o1,&$o2) { echo'o1==o2:'.bool2str($o1==$ o2)."n"; echo'o1!=o2:'.bool2str($o1!=$ o2)."n"; echo'o1===o2:'.bool2str($o1=== $o2)."n"; echo'o1!==o2:'.bool2str($o1!== $o2)."n"; } classFlag{ public$flag; functionFlag($flag=true){ $this->flag=$flag; } } www.facebook.com/VineetOO7
  • 79. classOtherFlag{ public$flag; functionOtherFlag($flag=true){ $this->flag=$flag; } } $o=newFlag(); $p=newFlag(); $q=$o; $r=newOtherFlag(); echo"Twoinstancesofthesameclassn"; compareObjects($o,$p); echo"nTworeferencestothesameinstancen"; compareObjects($o,$q); echo"nInstancesoftwodifferentclassesn"; compareObjects($o,$r); ?> Two instances of the same class o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : FALSE o1 !== o2 : TRUE Two references to the same instance o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE Instances of two different classes o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE www.facebook.com/VineetOO7
  • 80. Late Static Bindings HP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the::operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced byself::,parent::,static::, or, if going up in the class hierarchy,forward_static_call(). The functionget_called_class()can be used to retrieve a string with the name of the called class andstatic::introduces its scope This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact thatstatic::will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls. Limitations ofself:: Static references to the current class likeself::or__CLASS__are resolved using the class in which the function belongs, as in where it was defined: self::usage <?phpclassA{ publicstaticfunctionwho(){ echo__CLASS__; } publicstaticfunctiontest(){ self::who(); } } classBextendsA{ publicstaticfunctionwho(){ echo__CLASS__; } } B::test(); ?> The above example will output: A forward_static_call()-Call a static method www.facebook.com/VineetOO7
  • 81. Late Static Bindings' usage Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to referenceBfromtest()in the previous example. It was decided not to introduce a new keyword but rather usestaticthat was already reserved. Example #2static::simple usage <?phpclassA{ publicstaticfunctionwho(){ echo__CLASS__; } publicstaticfunctiontest(){ static::who();//HerecomesLateStaticBindings} } classBextendsA{ publicstaticfunctionwho(){ echo__CLASS__; } } B::test(); ?> The above example will output: B In non-static contexts, the called class will be the class of the object instance. Since$this->will try to call private methods from the same scope, usingstatic::may give different results. Another difference is thatstatic::can only refer to static properties. www.facebook.com/VineetOO7
  • 82. static::usage in a non-static context <?phpclassA{ privatefunctionfoo(){ echo"success!n"; } publicfunctiontest(){ $this->foo(); static::foo(); } } classBextendsA{ /*foo()willbecopiedtoB,henceitsscopewillstillbeAand*thecallbesuccessful*/ } classCextendsA{ privatefunctionfoo(){ /*originalmethodisreplaced;thescopeofthenewoneisC*/ } } $b=newB(); $b->test(); $c=newC(); $c->test();//fails?> The above example will output: success! success! success! Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords likeparent::orself::will forward the calling information. www.facebook.com/VineetOO7
  • 83. Objects and references One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples. A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessorsto find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. References and Objects <?phpclassA{ public$foo=1; } $a=newA; $b=$a;//$aand$barecopiesofthesameidentifier//($a)=($b)=<id> $b->foo=2; echo$a->foo."n"; $c=newA; $d=&$c;//$cand$darereferences//($c,$d)=<id> $d->foo=2; echo$c->foo."n"; $e=newA; functionfoo($obj){ //($obj)=($e)=<id> $obj->foo=2; } foo($e); echo$e->foo."n"; ?> The above example will output: 2 2 2 www.facebook.com/VineetOO7
  • 84. Object Serialization Serializing objects -objects in sessions serialize()returns a string containing a byte-stream representation of any value that can be stored in PHP.unserialize()can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class. In order to be able tounserialize()an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserializethis in another file, an object of class A, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of thespl_autoload_register()function. <?php//classa.inc: classA{ public$one=1; publicfunctionshow_one(){ echo$this->one; } } //page1.php: include("classa.inc"); $a=newA; $s=serialize($a); //store$ssomewherewherepage2.phpcanfindit. file_put_contents('store',$s); //page2.php: //thisisneededfortheunserializetoworkproperly. include("classa.inc"); $s=file_get_contents('store'); $a=unserialize($s); //nowusethefunctionshow_one()ofthe$aobject. $a->show_one(); ?> www.facebook.com/VineetOO7
  • 85. Namespaces What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: 1.Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants. 2.Ability to alias (or shorten) Extra_Long_Namesdesigned to alleviate the first problem, improving readability of source code. PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP: <?phpnamespacemyname;//see"DefiningNamespaces"sectionclassMyClass{} functionmyfunction(){} constMYCONST=1; $a=newMyClass; $c=newmynameMyClass;//see"GlobalSpace"section$a=strlen('hi');//see"Usingnamespaces:fallbacktoglobal//function/constant"section$d=namespaceMYCONST;//see"namespaceoperatorand__NAMESPACE__ //constant"section$d=__NAMESPACE__.'MYCONST'; echoconstant($d);//see"Namespacesanddynamiclanguagefeatures"section?> www.facebook.com/VineetOO7
  • 86. Defining namespaces Although any valid PHP code can be contained within a namespace, only four types of code are affected by namespaces: classes, interfaces, functions and constants. Namespaces are declared using thenamespacekeyword. A file containing a namespace must declare the namespace at the top of the file before any other code Declaring a single namespace <?phpnamespaceMyProject; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} ?> <html> <?phpnamespaceMyProject;//fatalerror-namespacemustbethefirststatementinthescript?> The only code construct allowed before a namespace declaration is thedeclarestatement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace: www.facebook.com/VineetOO7
  • 87. Declaring sub-namespaces Much like directories and files, PHP namespaces also contain the ability to specify a hierarchy of namespace names. Thus, a namespace name can be defined with sub-levels: <?phpnamespaceMyProjectSubLevel; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} ?>Defining multiple namespaces in the same file Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. <?phpnamespaceMyProject; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} namespaceAnotherProject; constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} ?> This syntax is not recommended for combining namespaces into a single file. www.facebook.com/VineetOO7
  • 88. Declaring multiple namespaces, bracketed syntax <?phpnamespaceMyProject{ constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} } namespaceAnotherProject{ constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} } ?> Declaring multiple namespaces and unnamespacedcode <?phpnamespaceMyProject{ constCONNECT_OK=1; classConnection{/*...*/} functionconnect(){/*...*/} } namespace{//globalcodesession_start(); $a=MyProjectconnect(); echoMyProjectConnection::start(); } ?> www.facebook.com/VineetOO7
  • 89. /*Unqualifiedname*/ foo();//resolvestofunctionFooBarfoofoo::staticmethod();//resolvestoclassFooBarfoo,methodstaticmethodechoFOO;//resolvestoconstantFooBarFOO/*Qualifiedname*/ subnamespacefoo();//resolvestofunctionFooBarsubnamespacefoosubnamespacefoo::staticmethod();//resolvestoclassFooBarsubnamespacefoo, //methodstaticmethodechosubnamespaceFOO;//resolvestoconstantFooBarsubnamespaceFOO/*Fullyqualifiedname*/ FooBarfoo();//resolvestofunctionFooBarfooFooBarfoo::staticmethod();//resolvestoclassFooBarfoo,methodstaticmethodechoFooBarFOO;//resolvestoconstantFooBarFOO?> file1.php <?phpnamespaceFooBarsubnamespace; constFOO=1; functionfoo(){} classfoo{ staticfunctionstaticmethod(){} } ?> file2.php <?phpnamespaceFooBar; include'file1.php'; constFOO=2; functionfoo(){} classfoo{ staticfunctionstaticmethod(){} } www.facebook.com/VineetOO7
  • 90. Using namespaces: Aliasing/Importing The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystemsto create symbolic links to a file or to a directory. PHP namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. Note that importing a function or constant is not supported. In PHP, aliasing is accomplished with theuseoperator. Here is an example showing all 3 kinds of importing: importing/aliasing with the use operator <?phpnamespacefoo; useMyFullClassnameasAnother; //thisisthesameasuseMyFullNSnameasNSnameuseMyFullNSname; //importingaglobalclassuseArrayObject; $obj=newnamespaceAnother;//instantiatesobjectofclassfooAnother$obj=newAnother;//instantiatesobjectofclassMyFullClassnameNSnamesubnsfunc();//callsfunctionMyFullNSnamesubnsfunc$a=newArrayObject(array(1));//instantiatesobjectofclassArrayObject//withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfooArrayObject?> www.facebook.com/VineetOO7
  • 91. Exception PHP 5 has an exception model similar to that of other programming languages. An exception can bethrown, and caught ("catched") within PHP. Code may be surrounded in atryblock, to facilitate the catching of potential exceptions. When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matchingcatchblock. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." Eachtrymust have at least one correspondingcatchblock. Multiplecatchblocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within thetryblock, or when acatchmatching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can bethrown (or re-thrown) within acatchblock. <?phpfunctioninverse($x){ if(!$x){ thrownewException('Divisionbyzero.'); } elsereturn1/$x; } try{ echoinverse(5)."n"; echoinverse(0)."n"; }catch(Exception$e){ echo'Caughtexception:',$e- >getMessage(),"n"; } //Continueexecutionecho'HelloWorld'; ?> www.facebook.com/VineetOO7
  • 92. <?phpclassMyExceptionextendsException{} classTest{ publicfunctiontesting(){ try{ try{ thrownewMyException('foo!'); }catch(MyException$e){ /*rethrowit*/ throw$e; } }catch(Exception$e){ var_dump($e->getMessage()); } } } $foo=newTest; $foo->testing(); ?> Nested / Custom Exception www.facebook.com/VineetOO7
  • 93. Exception Exceptionis the base class for all Exceptions. Exception::getMessage()example <?phptry{ thrownewException("Someerrormessage"); }catch(Exception$e){ echo$e->getMessage(); } ?> The above example will output something similar to: Some error message Exception::getPrevious()example Looping over, and printing out, exception trace. <?phpclassMyCustomExceptionextendsException{} functiondoStuff(){ try{ thrownewInvalidArgumentException("Youaredoingitwrong!",112); }catch(Exception$e){ thrownewMyCustomException("Somethinghappend",911,$e); } } try{ doStuff(); }catch(Exception$e){ do{ printf("%s:%d%s(%d)[%s]n",$e->getFile(),$e- >getLine(),$e->getMessage(),$e->getCode(),get_class($e)); }while($e=$e->getPrevious()); } ?> The above example will output something similar to: /home/bjori/ex.php:8 Something happend(911) [MyCustomException] /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException] www.facebook.com/VineetOO7
  • 94. Protocol support by php Filesystem ftp http www.facebook.com/VineetOO7
  • 95. Cookies PHP transparently supportsHTTPcookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using thesetcookie()function. Cookies are part of theHTTPheader, sosetcookie()must be called before any output is sent to the browser. Any cookies sent to you from the client will automatically be included into a$_COOKIEauto-global array setcookie setcookie()defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sentbeforeany output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including<html>and<head>tags as well as any whitespace. Once the cookies have been set, they can be accessed on the next page load with the$_COOKIEor$HTTP_COOKIE_VARSarrays. Cookie values also exist in$_REQUEST. Http protocol www.facebook.com/VineetOO7
  • 96. <?php$value='somethingfromsomewhere'; setcookie("TestCookie",$value); setcookie("TestCookie",$value,time()+3600);/*expirein1hour*/ setcookie("TestCookie",$value,time()+3600,"/~rasmus/","example.com",1); ?> setcookie()send example <?php//Printanindividualcookieecho$_COOKIE["TestCookie"]; echo$HTTP_COOKIE_VARS["TestCookie"]; //Anotherwaytodebug/testistoviewallcookiesprint_r($_COOKIE); ?> <?php//settheexpirationdatetoonehouragosetcookie("TestCookie","",time()-3600); setcookie("TestCookie","",time()- 3600,"/~rasmus/","example.com",1); ?> setcookie()delete www.facebook.com/VineetOO7
  • 97. <?php//setthecookiessetcookie("cookie[three]","cookiethree"); setcookie("cookie[two]","cookietwo"); setcookie("cookie[one]","cookieone"); //afterthepagereloads,printthemoutif(isset($_COOKIE['cookie'])){ foreach($_COOKIE['cookie']as$name=>$value) { $name=htmlspecialchars($name); $value=htmlspecialchars($value); echo"$name:$value<br/>n"; } } ?> The above example will output: three : cookiethreetwo : cookietwoone : cookieone www.facebook.com/VineetOO7
  • 98. Sessions Introduction Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. The session support allows you to store data between requests in the$_SESSIONsuperglobalarray www.facebook.com/VineetOO7
  • 99. boolsession_start(void) session_start()creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. session_start—Start new or resume existing session page1.php <?php//page1.phpsession_start(); echo'Welcometopage#1'; $_SESSION['favcolor']='green'; $_SESSION['animal']='cat'; $_SESSION['time']=time(); //Worksifsessioncookiewasacceptedecho'<br/><ahref="page2.php">page2</a>'; //Ormaybepassalongthesessionid,ifneededecho'<br/><ahref="page2.php?'.SID.'">page2</a>'; ?> page2.php <?php//page2.phpsession_start(); echo'Welcometopage#2<br/>'; echo$_SESSION['favcolor'];//greenecho$_SESSION['animal'];//catechodate('YmdH:i:s',$_SESSION['time']); //YoumaywanttouseSIDhere,likewedidinpage1.phpecho'<br/><ahref="page1.php">page1</a>'; ?> www.facebook.com/VineetOO7
  • 100. session_regenerate_id session_regenerate_id—Update the current session id with a newly generated one Asession_regenerate_id()example <?phpsession_start(); $old_sessionid=session_id(); session_regenerate_id(); $new_sessionid=session_id(); echo"OldSession:$old_sessionid<br/>"; echo"NewSession:$new_sessionid<br/>"; print_r($_SESSION); ?> www.facebook.com/VineetOO7
  • 101. session_name session_name—Get and/or set the current session name session_name()returns the name of the current session. Ifnameis given,session_name()will update the session name and return theoldsession name. session_name()example <?php/*setthesessionnametoWebsiteID*/ $previous_name=session_name("WebsiteID"); echo"Theprevioussessionnamewas$previous_name<br/>"; ?> stringsession_name([string$name] ) www.facebook.com/VineetOO7