Wednesday, October 05, 2005

PHP Tips -- Constant, Variable & Operator

Constant

Predefined constants
__FILE__ : The name of the file that the PHP engine is currently reading, contains the full path and filename of the current (i.e. included) file.

__LINE__ : The line number of the file.

PHP_VERSION : Current PHP version

How to Define Constants

if (!defined("NO")) define("NO", 0);
if (!defined("YES")) define("YES", 1);


Use constant

if ($answer == YES) return true;


VARIABLE

integer, double, string, boolean, object, array,
NULL, Resource(reference to a third-party resource(a db,for example))

Some related functions:

gettype($var)
settype($var, 'typestr'); // changes the original data type
(datatype)$var //use cast, like in C, doesn't change the original data type


A variable declared in a function remains local to that function ( not available to outside the function or within other functions.

A variable declared outside a function will not automatically be available within it.
To access for a global variable, you need to use the global statement in the function.

Use static to declare a static variable in a function
Ex.

$var1 = 1;
$var2 = 3;
function a()
{
static $svar1 = 0;
global $var1, $var2;

$svar++;
}




=== : Identical, Left is equivalent to right and they are the same type.

Ex:

$x = 4;
$x === 4; //true
$x === '4'; //flase

$teststr = "mz00xyz";
if (strpos($teststr, "mz") === 0) {
// returns index 0, which could be resolve to false.
// Use "===" can work around this,
// the condition will be true (false and 0 are diffrent data type)
echo"Hello mz";
}


Have a browse of the PHP Cheat Sheet

No comments: