Tuesday, March 27, 2007

PHP: Basic

Variable variables. I'm aware of variable variables in PHP however didn't notice this syntax before (using curly braces):

$var = 'some value'; $x = 'var'; print $x . "\n"; // will print var print $$x . "\n"; // will print some value print ${'x'} . "\n"; // will print var print ${'var'} . "\n"; // will print some value function fn($n) { print "fn($n)\n"; } $f = 'fn'; $f(2); // will print fn(2) ${'f'}(3); // will print fn(3)
Variable type casting. Like C/C++, you can do variable type casting:
$x = 3.14; echo (int) $x; // will print 3
Variable scope. PHP doesn't support namespace.
$a = 'aaa'; $b = 'bbb'; function fn() { global $a, $b; print $a . " " . $b . PHP_EOL; // will print aaa bbb } fn();
PHP share global variable scops which allows
$a = 'aaa'; $b = 'bbb'; function fn() { // will also print aaa bbb print $GLOBALS['a'] . " " . $GLOBALS['b'] . PHP_EOL; } fn();
Operator. Beside bitwise operators, here are the two operators I've seldom use: error suppression operator(@) and reference operator(&).
$result = @mysql_connect(); // will not display error $a = &$b; // copy by reference function &query(&$sql) { // pass by reference $result = mysql_query($sql); return $result; }
Function. The function names are case insensitive however variable names are.
function fnname() { print "fnname()" . PHP_EOL; } fNnAmE(); // will print fnname() $varname = "varname"; echo $vArNaMe; // will give error //PHP Notice: Undefined variable

No comments: