HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… ·...

46
HipHop for PHP: Move Fast

Transcript of HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… ·...

Page 1: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

HipHop for PHP: Move Fast

Page 2: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

• 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 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

HipHop for PHP: Move Fast

http://wiki.github.com/facebook/hiphop-php/building-and-installing

Page 3: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Parameter passing, calling functions, etc.

Page 4: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

<?php

function foo($arg_1, $arg_2, /* ..., */ $arg_n)

{

echo "Example function.\n";

return $retval;

}

?>

User-defined Functions

Page 5: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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.

Page 6: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

User-defined Functions

All functions and classes in PHP have the global scope.

Functions need not be defined before they are referenced…

Page 7: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Where to put the function implementation?

In PHP a function could be defined before or after it is called.

e.g.

<?php

analyseSystem();

function analyseSystem(){echo "analysing...";

}

?>

<?php

function analyseSystem(){echo "analysing...";

}

analyseSystem()?>

Page 8: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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

Page 9: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program
Page 10: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

<?php$makefoo = true;

/* We can't call foo() from heresince 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.

Page 11: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program
Page 12: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

<?php

function foo() {function bar() {echo "I don't exist until foo() is called.\n";

}}

/* We can't call bar() yetsince it doesn't exist. */

foo();

/* Now we can call bar(),foo()'s processesing hasmade 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.

Page 13: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Function reference

Always refer to:

http://nz2.php.net/manual/en/funcref.php

Page 14: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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

Page 15: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Variable scope

<?php

function function1(){

$strB ="B";

}

$strA="A";

echo $strB ;

echo "<br>";

echo $strA;

?>

$strB is not printed, as it has no value outside function1()

Local variable

Page 16: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

<?php

$a = 1; /* global scope */

function test(){

echo $a; /* reference to local scope variable */}

test();?>

Variable Scope

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

Treated as a Local variable

Another example

Page 17: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

• In PHP global variables must be declared global inside a function if they are going to be used in that function.

Variable Scope

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

<?php

$a = 1; /* global scope */

function test(){

echo $a; /* reference to local scope variable */}

test();?>

Not the same as C programming!

How can we fix this problem?

Page 18: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

• In PHP global variables must be declared global inside a function if they are going to be used in that function.

Variable Scope

<?php$a = 1;$b = 2;

function Sum(){

global $a, $b;

$b = $a + $b;}

Sum();echo $b;?>

This script will output 3.

This fixes the problem!

Page 19: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

• Alternative approach to accessing global variables inside a function

Variable Scope

<?php$a = 1;$b = 2;

function Sum(){

$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];}

Sum();echo $b;?>

This script will also output 3.

The $GLOBALS array is a superglobal variable with the name of the global variable being the key and the contents of that variable being the value of the array element.

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

Page 20: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Arguments

<?php

function myfunction1($arg1)

{

echo $arg1;

}

myfunction1("bla bla bla");

?>

By default, arguments are passed by value

Nothing about the type though...

Page 21: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Default arguments

<?phpfunction

myfunction1($arg1="D"){echo $arg1 . "<br>";}myfunction1("bla bla bla");$strA="A";myfunction1($strA);$intA=12;myfunction1($intA);myfunction1();

?>

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?

Page 22: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Default Arguments

<?phpfunction makecoffee($type = "cappuccino"){

return "Making a cup of $type.\n";}echo makecoffee();echo makecoffee(null);echo makecoffee("espresso");?>

Making a cup of cappuccino. Making a cup of . Making a cup of espresso.

output

Page 23: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Default Arguments

<?phpfunction makeRobot($type = "attacker“, $colour){

return "Making an $type robot, colour = $colour.\n";}

echo makeRobot("blue"); // won't work as expected?>

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

output

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:

Page 24: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Default Arguments

<?phpfunction makeRobot($colour, $type = "attacker"){

return "Making an $type robot, colour = $colour.\n";}

echo makeRobot("blue"); // won't work as expected?>

Making an attacker robot, colour = blue.

output

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:

Page 25: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Returning a value

<?phpfunction 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>";?> What if nothing is

returned?

Page 26: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

No return() means NULL

<?phpfunction 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 omitted the value NULL will be returned.

Page 27: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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"));

?>

Use arrays...

Or pass args by reference

Page 28: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Passing args by reference

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

Somewhat like C

Except that its much easier to make a mistake...

Page 29: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Calling function within functions

<?phpfunction A($arg1){

echo $arg1 . "<br>";}

function B(){return "this is function B";

}

echo A(B());

?>

Page 30: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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);?>

Be extremely careful as the program might not stop calling itself!!

• avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.

Page 31: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program
Page 32: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Basic include() example

<?php

$color = 'green';$fruit = 'apple';

?>

<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

vars.php

test.php Execution is from top to bottom.

The two variables are seen for the first time here.

Page 33: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Separating source files

Use:

include();

include_once();

Difference:

include_once() does notinclude the contents of a file twice, if a mistake was made.

it may help avoid problems such as function redefinitions, variable value reassignments, etc.

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_WARNINGwhich allows the script to continue.

Page 34: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Variable Variables

$$VAR

If $var = 'foo' and $foo = 'bar' then $$varwould contain the value 'bar'

• $$var can be thought of as $'foo' which is simply $foo which has the value 'bar'.

Page 35: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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

?>

Page 36: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

<?phpfunction 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()

?>

myfunctionEchoing from myfunction.Echoing from myfunction.

output

Variable Variables

What does $$VAR mean?

Page 37: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Variable variables?

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

Variable variable makes it easy to read the config file and create corresponding variables:

foo=bar#commentabc=123

config.txt

A more useful example

Page 38: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

getdate()

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

The getdate() function returns an array that contains date and time information for a Unix timestamp.

Array([seconds] => 45[minutes] => 52[hours] => 14[mday] => 24[wday] => 2[mon] => 1[year] => 2006[yday] => 23[weekday] => Tuesday[month] => January[0] => 1138110765)

Page 39: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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'

Page 40: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Example

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

Monday, September 13, 2010

Sample output:

date() function is used to format a time and/or date.

Page 41: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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

Page 42: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

<?php

function microtime_float(){

list($usec, $sec) = explode(" ", microtime());return ((float)$usec + (float)$sec);

}

$time_start = microtime_float();

// Sleep for a whileusleep(100);

$time_end = microtime_float();$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";?>

Calculating the Elapsed time

Page 43: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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));?>

bool(true) bool(false)

output:

This function displays structured information about one or more expressions that includes its type and value.

Page 44: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

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 seedthe random number generator with srand()

Page 45: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

Random numbers example

<?php

srand( (double) microtime() * 100000000);

$intMyNumber = rand(1,40);

echo "My next lucky number for winning Lotto is $intMyNumber<br>";

?>

Page 46: HipHop for PHP: Move Fast - Massey Universitynhreyes/MASSEY/159339/Lectures/Lect… · 5.3.3\www\phptest\Lecture14\function_default_missing.php on line 7 and defined in C:\Program

File Submission System