12/15/06

Zend Cert Tips --PHP Basics

  • Getting string offsets, {} is a better practice than [] note that indices are started from zero
  • Indirect references to variables(variable variables):

$name="John";

$$name="Registered User";

echo $john; //prints registered user

echo $name; //prints John

Variable variables are a very powerful tool, and should be used with extreme care, not only because they can make your code difficult to understand and document, but also because their improper use can lead to some significant security issues.

Because of the availability of variable variables, it is indeed possible to create variables whose names do not follow the constraints. This is also possible

by defining the name between braces:

$name = '123';

/* 123 is your variable name, this would normally be invalid. */

$$name = '456'; // Again, you assign a value

echo ${’123’}; // Finally, using curly braces you can output ’456’

A technique similar to variable variables can also be used to hold function names

inside a variable:

function myFunc() {

echo ’myFunc!’;

}

$f = ’myFunc’;

$f(); // will call myFunc();

Clearly, this technique should be used with as much care as variable variables,

opportunities for mistakes and security issues it raises are quite significant.

  • In heredoc ending statement, semicolon is optinal but newline is registered and no space should be before this statement:

$string= <<<>

Str

STRING; //no space should be b4 this

  • Using each() to work like foreach

$players=array("Joe","Jack","Bill");

Reset($players);

While(list($key,$val(\)=each($players)){

Echo "#$key=$val \n";

}

  • The third argument of define() sets the case insensitivity of the constant, default 1(insensitive)
  • Valid composite assignment operators:

+= -= %= ^= .= &= |= <<= >>=

  • The match in the switch statement uses == not ===
  • For "for" loop we can supply more than one expression for each of the three args by using commas to delimit them.
  • Using "global" keyword is not recommended because of various reasons such as misbehaving with assigning values by reference, not supporting unset() and so on. We should use $_GLOBALS[] instead