1 / 46

Some interesting news

Some interesting news. HipHop for PHP : Move Fast. HipHop for PHP: Move Fast. PHP's roots are those of a scripting language , like Perl, Python, and Ruby, all of which have major benefits in terms of programmer productivity and the ability to iterate quickly on products.

Download Presentation

Some interesting news

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Some interesting news HipHop for PHP: Move Fast

  2. HipHop for PHP: Move Fast • PHP's roots are those of a scripting language, like Perl, Python, and Ruby, all of which have major benefits in terms of programmer productivity and the ability to iterate quickly on products. • On the other hand, scripting languages are known to be far less efficient when it comes to CPU and memory usage. • Because of this, it's been challenging to scale Facebook to over 400 billion PHP-based page views every month. • ScalingFacebook is particularly challenging because almost every page view is a logged-in user with a customized experience. When you view your home page we need to look up all of your friends, query their most relevant updates (from a custom service we've built called Multifeed), filter the results based on your privacy settings, then fill out the stories with comments, photos, likes, and all the rich data that people love about Facebook. All of this in just under a second. • HipHop allows us to write the logic that does the final page assembly in PHP and iterate it quickly while relying on custom back-end services in C++, Erlang, Java, or Python to service the News Feed, search, Chat, and other core parts of the site. http://www.facebook.com/note.php?note_id=280583813919&id=9445547199 http://wiki.github.com/facebook/hiphop-php/building-and-installing

  3. Functions Parameter passing, calling functions, etc.

  4. User-defined Functions • <?php • functionfoo($arg_1, $arg_2, /* ..., */ $arg_n) • { • echo "Example function.\n"; • return$retval; • } • ?>

  5. User-defined Functions • Any valid PHP code may appear inside a function, even other functions and class definitions. • A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. • PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions. • Both variable number of arguments and default arguments are supported in functions.

  6. User-defined Functions • All functionsand classesin PHP have the global scope. • Functions need not be defined before they are referenced…

  7. Where to put the function implementation? • In PHP a function could be defined before or after it is called. • e.g. <?php function analyseSystem(){ echo "analysing..."; } analyseSystem() ?> <?php analyseSystem(); function analyseSystem(){ echo "analysing..."; } ?>

  8. User-defined Functions • All functionsand classesin PHP have the global scope. • Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the next example.

  9. Conditional Functions

  10. <?php$makefoo= true;/* We can't call foo() from here    since it doesn't exist yet,   but we can call bar() */bar();if ($makefoo) {function foo()   {     echo "I don't exist until program execution reaches me.\n";   }}/* Now we can safely call foo()   since $makefoo evaluated to true */if ($makefoo) foo();function bar() {   echo "I exist immediately upon program start.\n";}?> Conditional Functions A function inside an if statement. The function cannot be called not until the if statement is executed with a satisfying result.

  11. Functions with Functions

  12. <?php function foo() { function bar() { echo "I don't exist until foo() is called.\n"; } } /* We can't call bar() yet since it doesn't exist. */ foo(); /* Now we can call bar(), foo()'s processesing has made it accessible. */ bar(); ?> Functions with Functions 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.

  13. Function reference • Always refer to: • http://nz2.php.net/manual/en/funcref.php

  14. Variable Scope • global variables • local variables • how to access global variables inside a function

  15. $strBis not printed, as it has no value outside function1() Variable scope • <?php • function function1(){ • $strB="B"; • } • $strA="A"; • echo$strB; • echo"<br>"; • echo$strA; • ?> Local variable

  16. Variable Scope Another example <?php$a = 1; /* global scope */ function test(){     echo $a; /* reference to local scope variable */} test();?> Treated as a Local variable • This will not produce any output! • the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope.

  17. Variable Scope • In PHP global variables must be declared globalinside a function if they are going to be used in that function. Not the same as C programming! How can we fix this problem? <?php$a = 1; /* global scope */ function test(){     echo $a; /* reference to local scope variable */} test();?> • This will not produce any output! • the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope.

  18. Variable Scope • In PHP global variables must be declared globalinside a function if they are going to be used in that function. <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> This fixes the problem! This script will output 3.

  19. Variable Scope • Alternative approach to accessing global variables inside a function The $GLOBALS array is a superglobal variable with the name of the global variable being the keyand the contentsof that variable being the value of the array element. <?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?> This script will also output3. $GLOBALS -an associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

  20. By default, arguments are passed by value Nothing about the type though... Arguments • <?php • function myfunction1($arg1) • { • echo $arg1; • } • myfunction1("bla bla bla"); • ?>

  21. No args passed would mean using the default values Sometimes useful Again, nothing about types... Default arguments • <?php • function myfunction1($arg1="D"){ • echo $arg1 . "<br>"; • } • myfunction1("bla bla bla"); • $strA="A"; • myfunction1($strA); • $intA=12; • myfunction1($intA); • myfunction1(); • ?> What if we pass NULLas a parameter to our function?

  22. Default Arguments <?phpfunction makecoffee($type = "cappuccino"){    return "Making a cup of $type.\n";}echo makecoffee();echo makecoffee(null);echo makecoffee("espresso");?> output Making a cup of cappuccino. Making a cup of . Making a cup of espresso.

  23. Default Arguments Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet: <?php function makeRobot($type = "attacker“, $colour) { return "Making an $type robot, colour = $colour.\n"; } echo makeRobot("blue"); // won't work as expected ?>  output Warning: Missing argument 2 for makeRobot(), called in C:\Program Files\EasyPHP-5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program Files\EasyPHP-5.3.3\www\phptest\Lecture14\function_default_missing.php on line 2

  24. Default Arguments Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet: <?php function makeRobot($colour, $type = "attacker") { return "Making an $type robot, colour = $colour.\n"; } echo makeRobot("blue"); // won't work as expected ?>  output Making an attacker robot, colour = blue.

  25. What if nothing is returned? Returning a value • <?php • function myfunction1($arg1="A"){ • if ($arg1 === "A")return 100; • else return 200; • } • echo myfunction1("bla bla bla") . "<br>"; • $strA="A"; • echo myfunction1($strA) . "<br>"; • $intA=12; • echo myfunction1($intA) . "<br>"; • echo myfunction1() . "<br>"; • ?>

  26. No return() means NULL • <?php • function addone(&$n){ • //return ++$n; • ++$n;//would expect that $n is added without returning a value • } • function multiplyseq($n) • { • return ( addone(&$n) * $n ); • //if addone($n) is NULL, anything multiplied by it results to zero • } • echo multiplyseq(2); • ?> • If the return() is omittedthe value NULLwill be returned.

  27. Use arrays... Or pass args by reference Returning more than one value • <?php • function multipleret($arg1){ • $arrResult=array(); • $arrResult[]="A"; • $arrResult[]=$arg1; • $arrResult[]=1.25; • return $arrResult; • } • print_r(multipleret("bla bla bla")); • ?>

  28. Somewhat like C Except that its much easier to make a mistake... Passing args by reference • <?php • function add_some_extra(&$string) • { • $string .= 'and something extra.'; • } • $str= 'This is a string, '; • add_some_extra($str); • echo $str; // outputs 'This is a string, and something extra.' • ?>

  29. Calling function within functions • <?php • function A($arg1){ • echo $arg1 ."<br>"; • } • function B(){ • return "this is function B"; • } • echo A(B()); • ?>

  30. Be extremely careful as the program might not stop calling itself!! Recursive functions • <?php • function recur($intN){ • if ($intN ==1) • return "this is a power of 2<br>"; • elseif ($intN%2 == 1) • return "not a power of 2<br>"; • else { • $intN /=2; • return recur($intN); • } • } • echo "256: " . recur(256); • echo "1024: " . recur(1024); • echo "1025: " . recur(1025); • ?> • avoid recursive function/method calls with over 100-200recursion levels as it can smash the stack and cause a terminationof the current script.

  31. Codes in multiple files

  32. Basic include() example vars.php <?php$color = 'green';$fruit= 'apple';?> Execution is from top to bottom. The two variables are seen for the first time here. test.php <?phpecho "A $color  $fruit"; // Ainclude 'vars.php';echo "A $color $fruit"; // A green apple?>

  33. Alternatively: require(); require_once(); If the file to be included is not found, the script is terminated by require(). Upon failure, include() only emits an E_WARNING which allows the script to continue. Separating source files • Use: • include(); • include_once(); • Difference: • include_once() does not include the contents of a file twice, if a mistake was made. • it may help avoid problems such as function redefinitions, variable value reassignments, etc.

  34. Variable Variables • $$VAR • If $var= 'foo' and $foo= 'bar' then $$varwould contain the value 'bar' • $$varcan be thought of as $'foo' which is simply $foowhich has the value 'bar'.

  35. Obsfuscation... • <?php • function myfunction(){ • echo "Echoing from myfunction<br>"; • } • $str = 'myfunction'; • $myfunction_1 = "myfunction"; • echo ${$str.'_1'}; • $str(); // Calls a function named myfunction() • ${$str.'_1'}(); // Calls a function named function_1()? • myfunction_1(); //or maybe not... • ?>

  36. Variable Variables • What does $$VAR mean? <?php function myfunction(){ echo "<br>Echoing from myfunction."; } $str = 'myfunction'; $myfunction_1 = "myfunction"; echo ${$str.'_1'}; $str(); // Calls a function named myfunction() ${$str.'_1'}(); // Calls a function named myfunction() ?> output myfunction Echoing from myfunction. Echoing from myfunction.

  37. Variable variable makes it easy to read the config file and create corresponding variables: Variable variables? A more useful example • <?php • $fp = fopen('config.txt','r'); • while(true) { • $line = fgets($fp,80); • if(!feof($fp)) { • if($line[0]=='#' || strlen($line)<2) continue; • list($name,$val)=explode('=',$line,2); • $$name=trim($val); • echo $name . " = ". $val ."<br>"; • } else break; • } • fclose($fp); • ?> • from http://talks.php.net/show/tips/7 config.txt foo=bar #comment abc=123

  38. getdate() The getdate() function returns an array that contains date and time information for a Unix timestamp. The returning array contains ten elements with relevant information needed when formatting a date string: [seconds] - seconds [minutes] - minutes [hours] - hours [mday] - day of the month [wday] - day of the week [year] - year [yday] - day of the year [weekday] - name of the weekday [month] - name of the month Array([seconds] => 45[minutes] => 52[hours] => 14[mday] => 24[wday] => 2[mon] => 1[year] => 2006[yday] => 23[weekday] => Tuesday[month] => January[0] => 1138110765)

  39. Date/time functions • $arrMyDate = getdate(); • $intSec = $arrMyDate['seconds']; • $intMin = $arrMyDate['minutes']; • $intHours = $arrMyDate['hours']; • Etc, e.g., ints 'mday', 'wday', 'mon', 'year', 'yday' • Strings 'weekday', 'month'

  40. Example <?php$my_t=getdate(date("U"));print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]");?> date() function is used to format a time and/or date. Sample output: Monday, September 13, 2010

  41. Time • Microtime(); • Returns string 'msec sec' • e.g. <?php $strMyTime = microtime(); Echo “$strMyTime”; ?> • sec since 1st January 1970 (from UNIX...) • msec dec fraction of the time

  42. Calculating the Elapsed time <?php function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } $time_start = microtime_float(); // Sleep for a while usleep(100); $time_end = microtime_float(); $time = $time_end - $time_start; echo "Did nothing in $time seconds\n"; ?>

  43. Checking date • checkdate(m, d, y); • Returns bool • Returns TRUE if the date given is valid; otherwise returns FALSE. <?phpvar_dump(checkdate(12, 31, 2000));var_dump(checkdate(2, 29, 2001));?> This function displays structured information about one or more expressions that includes its type and value. output: bool(true) bool(false)

  44. Generating random numbers • What is the use of random numbers? • Similar to C: • srand (seed); • $intMynumber = rand(); or • $intMynumber = rand(start, end);  Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand()

  45. Random numbers example • <?php • srand( (double) microtime() * 100000000); • $intMyNumber = rand(1,40); • echo "My next lucky number for winning Lotto is $intMyNumber<br>"; • ?> 

  46. File Submission System

More Related