Some interesting news

46
HipHop HipHop for for PHP PHP : Move Fast : Move Fast

description

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. - PowerPoint PPT Presentation

Transcript of Some interesting news

Page 1: Some interesting news

HipHopHipHop for for PHPPHP: Move Fast: Move Fast

Page 2: Some interesting news

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

• ScalingScaling Facebook is particularly challenging because almost every page view is a logged-in user with a customized experiencecustomized 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.

• HipHopHipHop 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 FastHipHop for PHP: Move Fast

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

Page 3: Some interesting news

Parameter passing, calling functions, etc.Parameter passing, calling functions, etc.

Page 4: Some interesting news

<?php

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

{

echo "Example function.\n";

return $retval;

}

?>

User-defined FunctionsUser-defined Functions

Page 5: Some interesting news

User-defined FunctionsUser-defined Functions Any valid PHP codevalid PHP code may appear inside a

function, even other functions and class definitions.

A valid function name 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 variable number of arguments and default argumentsdefault arguments are supported in functions.

Page 6: Some interesting news

User-defined FunctionsUser-defined Functions

All functionsfunctions and classesclasses in PHP have the global scopeglobal scope.

Functions need not be defined before they are referenced…

Page 7: Some interesting news

Where to put the function Where to put the function implementation?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: Some interesting news

User-defined FunctionsUser-defined Functions

All functionsfunctions and classesclasses in PHP have the global scopeglobal scope.

Functions need not be defined before they are referenced, except when a function is conditionally defined conditionally defined as shown in the next example.

Page 9: Some interesting news
Page 10: Some interesting news

<?php$makefoo$makefoo = true;

/* We can't call foo()foo() from here    since it doesn't exist yet,   but we can call bar()bar() */

bar();

if ($makefoo$makefoo) {   function foofoo()   {     echo "I don't exist until program execution reaches me.\n";   }}

/* Now we can safely call foo()foo()   since $makefoo$makefoo evaluated to true */

if ($makefoo$makefoo) foo();

function bar() {   echo "I exist immediately upon program start.\n";}?>

Conditional Conditional FunctionsFunctions

A function inside an if statement.

The function cannot be The function cannot be called not until the if called not until the if statement is executed statement is executed with a satisfying result.with a satisfying result.

Page 11: Some interesting news
Page 12: Some interesting news

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

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: Some interesting news

Function referenceFunction reference

Always refer to: http://nz2.php.net/manual/en/funcref.phphttp://nz2.php.net/manual/en/funcref.php

Page 14: Some interesting news

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

Page 15: Some interesting news

Variable scopeVariable scope

<?php

function function1(){

$strB $strB ="B";

}

$strA="A";

echo $strB $strB ;

echo "<br>";

echo $strA;

?>

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

Local variable

Page 16: Some interesting news

<?php$a$a = 1; /* global scope */ 

function test(){     echo $a$a; /* reference to local scope variable */ } 

test();?>

Variable ScopeVariable Scope

• This will not produce any output! This will not produce any output! • the echo statement refers to a local version of the $a$a variable, and it has not been assigned a value within this scope.

Treated as a Local variable

Another example

Page 17: Some interesting news

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

Variable ScopeVariable Scope

• This will not produce any output! This will not produce any output! • the echo statement refers to a local version of the $a$a variable, and it has not been assigned a value within this scope.

<?php$a$a = 1; /* global scope */ 

function test(){     echo $a$a; /* reference to local scope variable */ } 

test();?>

Not the same as C programming!

How can we fix this problem?

Page 18: Some interesting news

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

Variable ScopeVariable Scope

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

function Sum(){ globalglobal $a, $b; $a, $b;

$b = $a + $b;}

Sum();echo $b;$b;?>

This script will output 3. 3.

This fixes the problem!

Page 19: Some interesting news

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

Variable ScopeVariable Scope

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

function Sum(){ $GLOBALS$GLOBALS['b'] = $GLOBALS$GLOBALS['a'] + $GLOBALS$GLOBALS['b'];}

Sum();echo $b;?>

This script will also output 3. 3.

The $GLOBALS $GLOBALS array is a superglobal variablesuperglobal variable with the name of the global variable being the keykey and the contentscontents of that variable being the value of the array element.

$GLOBALS $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: Some interesting news

ArgumentsArguments

<?php

function myfunction1($arg1)

{

echo $arg1;

}

myfunction1("bla bla bla");

?>

By default, arguments are passed by value

Nothing about the type though...

Page 21: Some interesting news

Default argumentsDefault 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 NULLNULL as a

parameter to our function?

Page 22: Some interesting news

Default ArgumentsDefault Arguments

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

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

output

Page 23: Some interesting news

Default ArgumentsDefault 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: Some interesting news

Default ArgumentsDefault 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: Some interesting news

Returning a valueReturning 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: Some interesting news

No return() means NULLNo 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 omittedomitted the value NULLNULL will be returned.

Page 27: Some interesting news

Returning more than one Returning more than one valuevalue

<?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: Some interesting news

Passing args by referencePassing 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: Some interesting news

Calling function within Calling function within functionsfunctions

<?phpfunction A($arg1){ echo $arg1 . "<br>";}

function B(){ return "this is function

B";}

echo A(B());

?>

Page 30: Some interesting news

Recursive functionsRecursive 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 recursion levelslevels as it can smash the stack and cause a terminationtermination of the current script.

Page 31: Some interesting news
Page 32: Some interesting news

Basic include() exampleBasic include() example

<?php

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

?>

<?php

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

include 'vars.phpvars.php';

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

?>

vars.phpvars.php

test.php Execution is from top to Execution is from top to bottom. bottom.

The two variables are The two variables are seen for the first time seen for the first time here.here.

Page 33: Some interesting news

Separating source files Separating source files

Use: include();include(); include_once();include_once();

Difference: include_once() 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.

Alternatively: require();require(); require_once();require_once(); If the file to be

included is not found, the script is terminated terminated by require()require().

Upon failure, include() include() only emits an E_WARNINGE_WARNING which allows the script to continue.

Page 34: Some interesting news

Variable VariablesVariable Variables$$VAR

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

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

Page 35: Some interesting news

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: Some interesting news

<?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 VariablesVariable VariablesWhat does $$VAR mean?

Page 37: Some interesting news

Variable variables?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: Some interesting news

getdate()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: Some interesting news

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: Some interesting news

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: Some interesting news

TimeTime

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: Some interesting news

<?php

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

Page 43: Some interesting news

Checking date checkdate(m, d, y);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 This function displays displays structured information structured information about one or more about one or more expressions that expressions that includes its includes its typetype and and valuevalue..

Page 44: Some interesting news

Generating random numbers

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

srand (seed);srand (seed); $intMynumber = rand(); rand(); or $intMynumber = rand(start, end);rand(start, end);

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand()srand()

Page 45: Some interesting news

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: Some interesting news

File Submission SystemFile Submission System