Some interesting news Hip Hop for PHP Move

  • Slides: 46
Download presentation
Some interesting news Hip. Hop for PHP: Move Fast

Some interesting news Hip. Hop for PHP: Move Fast

Hip. Hop for PHP: Move Fast • PHP's roots are those of a scripting

Hip. Hop 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. • Scaling Facebook is particularly challenging because almost every page view is a logged-in user with a customized experience. When you view your home customized experience 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. • Hip. Hop allows us to write the logic that does the final page assembly in PHP Hip. Hop 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

Functions Parameter passing, calling functions, etc.

Functions Parameter passing, calling functions, etc.

User-defined Functions <? php function foo($arg_1, $arg_2, /*. . . , */ $arg_n) foo

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

User-defined Functions Any valid PHP code may appear inside a valid PHP code function,

User-defined Functions Any valid PHP code may appear inside a valid PHP code function, even other functions and class definitions. A valid function name starts with a letter or function name 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 variable number of arguments default arguments are supported in functions. default arguments

User-defined Functions All functions and classes in PHP have the global scope Functions need

User-defined Functions All functions and classes in PHP have the global scope Functions need not be defined before they are referenced…

Where to put the function implementation? In PHP a function could be defined before

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

User-defined Functions All functions and classes in PHP have the global scope Functions need

User-defined Functions All functions and classes in 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 conditionally defined example.

Conditional Functions

Conditional Functions

<? php $makefoo = true; $makefoo /* We can't call foo() from here foo()

<? php $makefoo = true; $makefoo /* We can't call foo() from here foo() since it doesn't exist yet, but we can call bar() */ bar() Conditional Functions bar(); if ($makefoo) { $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 */ $makefoo if ($makefoo) $makefoo foo(); function bar() { echo "I exist immediately upon program start. n"; } ? > A function inside an if statement. The function cannot be called not until the if statement is executed with a satisfying result.

Functions with Functions

Functions with Functions

<? php function foo() { function bar() { echo "I don't exist until foo()

<? 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.

Function reference Always refer to: http: //nz 2. php. net/manual/en/funcref. php

Function reference Always refer to: http: //nz 2. php. net/manual/en/funcref. php

Variable Scope • global variables • local variables • how to access global variables

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

Variable scope <? php function 1(){ $str. B ="B"; $str. B } $str. A="A";

Variable scope <? php function 1(){ $str. B ="B"; $str. B } $str. A="A"; echo $str. B ; $str. B echo " "; echo $str. A; ? > $str. B is not printed, $str. B as it has no value outside function 1() Local variable

Variable Scope Another example <? php $a = 1; /* global scope */ $a

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

Variable Scope • In PHP global variables must be declared global variables global inside

Variable Scope • In PHP global variables must be declared global variables global inside a function if they are going to be used in that function. <? php $a = 1; /* global scope */ $a Not the same as C programming! How can we fix function test() this problem? { echo $a; $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 $a value within this scope.

Variable Scope • In PHP global variables must be declared global variables global inside

Variable Scope • In PHP global variables must be declared global variables global inside 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.

Variable Scope • Alternative approach to accessing global Alternative approach variables inside a function

Variable Scope • Alternative approach to accessing global Alternative approach variables inside a function The $GLOBALS array is a $GLOBALS superglobal variable with the superglobal variable name of the global variable being the key and the contents of that variable being the value of the array function Sum() element. { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; $GLOBALS } <? php $a = 1; $b = 2; Sum(); echo $b; ? > This script will also output 3. $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.

Arguments <? php function myfunction 1($arg 1) { echo $arg 1; } myfunction 1("bla

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

Default arguments <? php function myfunction 1($arg 1="D"){ echo $arg 1. " "; }

Default arguments <? php function myfunction 1($arg 1="D"){ echo $arg 1. " "; } myfunction 1("bla bla"); $str. A="A"; myfunction 1($str. A); $int. A=12; myfunction 1($int. A); myfunction 1(); ? > No args passed would mean using the default values Sometimes useful Again, nothing about types. . . What if we pass NULL as a parameter to our function?

Default Arguments <? php function makecoffee($type = "cappuccino") { return "Making a cup of

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

Default Arguments Note that when using default arguments, any defaults should be on the

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 make. Robot($type = "attacker“, $colour) { return "Making an $type robot, colour = $colour. n"; } echo make. Robot("blue"); // won't work as expected ? > output Warning: Missing argument 2 for make. Robot(), called in C: Program FilesEasy. PHP 5. 3. 3wwwphptestLecture 14function_default_missing. php on line 7 and defined in C: Program FilesEasy. PHP-5. 3. 3wwwphptestLecture 14function_default_missing. php on line 2

Default Arguments Note that when using default arguments, any defaults should be on the

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 make. Robot($colour, $type = "attacker") { return "Making an $type robot, colour = $colour. n"; } echo make. Robot("blue"); // won't work as expected ? > output Making an attacker robot, colour = blue.

Returning a value <? php function myfunction 1($arg 1="A"){ if ($arg 1 === "A")return

Returning a value <? php function myfunction 1($arg 1="A"){ if ($arg 1 === "A")return 100; else return 200; } echo myfunction 1("bla bla"). " "; $str. A="A"; echo myfunction 1($str. A). " "; $int. A=12; echo myfunction 1($int. A). " "; echo myfunction 1(). " "; What if nothing is ? > returned?

No return() means NULL <? php function addone(&$n){ //return ++$n; //would expect that $n

No return() means NULL <? php function addone(&$n){ //return ++$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 } If the return() is echo multiplyseq(2); ? > omitted the value NULL will be returned.

Returning more than one value <? php function multipleret($arg 1){ $arr. Result=array(); $arr. Result[]="A";

Returning more than one value <? php function multipleret($arg 1){ $arr. Result=array(); $arr. Result[]="A"; $arr. Result[]=$arg 1; $arr. Result[]=1. 25; return $arr. Result; } print_r(multipleret("bla bla")); ? > Use arrays. . . Or pass args by reference

Passing args by reference Somewhat like C <? php Except that its function add_some_extra(&$string)

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

Calling function within functions <? php function A($arg 1){ echo $arg 1. " ";

Calling function within functions <? php function A($arg 1){ echo $arg 1. " "; } function B(){ return "this is function B"; } echo A(B()); ? >

Recursive functions <? php Be extremely careful as the program might not stop calling

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

Codes in multiple files

Codes in multiple files

Basic include() example vars. php <? php $color = 'green'; $color $fruit = 'apple';

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

Separating source files Use: Alternatively: include(); require(); include_once(); require_once(); If the file to be

Separating source files Use: Alternatively: include(); require(); include_once(); require_once(); If the file to be included is not found, the script is terminated by terminated require() Upon failure, include() only emits include() an E_WARNING which allows the script to continue. Difference: include_once() does not include_once() 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.

Variables $$VAR If $var = 'foo' and $foo = 'bar' then $ $var would

Variables $$VAR If $var = 'foo' and $foo = 'bar' then $ $var would contain the value 'bar' • $$var can be thought of as $'foo' which is $var simply $foo which has the value 'bar'.

Obsfuscation. . . <? php function myfunction(){ echo "Echoing from myfunction "; } $str

Obsfuscation. . . <? php function myfunction(){ echo "Echoing from myfunction "; } $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. . . ? >

Variables What does $$VAR mean? <? php function myfunction(){ echo " Echoing from myfunction.

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

Variable variables? A more useful example <? php config. txt $fp = fopen('config. txt',

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

getdate() The getdate() function returns an array that contains date and time information for

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 )

Date/time functions $arr. My. Date = getdate(); $int. Sec = $arr. My. Date['seconds']; $int.

Date/time functions $arr. My. Date = getdate(); $int. Sec = $arr. My. Date['seconds']; $int. Min = $arr. My. Date['minutes']; $int. Hours = $arr. My. Date['hours']; Etc, e. g. , ints 'mday', 'wday', 'mon', 'year', 'yday' Strings 'weekday', 'month'

Example <? php $my_t=getdate("U")); print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]"); ? > date() function is used

Example <? php $my_t=getdate("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

Time Microtime(); Returns string 'msec sec' e. g. <? php $str. My. Time =

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

Calculating the Elapsed time <? php function microtime_float() { list($usec, $sec) = explode(" ",

Calculating the Elapsed time <? php function microtime_float() { list($usec, $sec) = explode(" ", microtime()); 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 secondsn"; ? >

Checking date checkdate(m, d, y); Returns bool Returns TRUE if the date given is

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

Generating random numbers What is the use of random numbers? Similar to C: srand

Generating random numbers What is the use of random numbers? Similar to C: srand (seed); $int. Mynumber = rand(); or rand(); $int. Mynumber = rand(start, end); Note: As of PHP 4. 2. 0, there is no need to seed the random number generator with srand()

Random numbers example <? php srand( (double) microtime() * 10000); $int. My. Number =

Random numbers example <? php srand( (double) microtime() * 10000); $int. My. Number = rand(1, 40); echo "My next lucky number for winning Lotto is $int. My. Number "; ? >

File Submission System

File Submission System