Sunday, May 27, 2007

Function and Class Syntax

PHP
Function Example
function inc($val)
{ return $val + 1;}

Procedures are functions that return no value.

Class Example
class parent {
var property;
function parent() { }
function method() { }
}

/* inheritance */
class child extends parent {
var property='new value';
}
Scope of Variables Variables defined outside a function or class are available globally; variables defined in a class or function are available locally.Unlike other languages, you must declare a global variable in a function or class before you use the variable, using the keyword global.
$globalvar = 1;
function show_global( )
{
global $globalvar;
print $globalvar;
}
Call by Reference Use & keyword in function parameters.
Default Parameters Yes.function A(param1=”abc”)
Returning by Reference By default, return is by value. For objects and arrays, we want to return by reference for superior performance. Use
function & getarray123() {
$val = array(1,2,3);
return $val;
}

Then in the calling code, use

 $val = &getarray123();

No comments: