4.PHP Functions

1. Defining a Function
function some_function( $argument1, $argument2 ) 
{ // function code here } 


2. Returning Values
<?php  function addNums( $firstnum, $secondnum ) 
{
 $result = $firstnum + $secondnum;  
 return $result; 
}
print addNums(3,5); 
// will print "8" 
?> 


3. Variable Scope
<?
php function test() 
{
$testvariable = "this is a test variable"; 
}
print "test variable:$testvariable<br/>"; 
?> 


4. Accessing global variables
<?php $life = 42; 
function meaningOfLife() 

print "The meaning of life is $life<br />"; 

 meaningOfLife(); 
 ?> 


5. Using the global keyword
<?php $life=42; 
function meaningOfLife() {
global $life; 
print "The meaning of life is $life<br />"; } 
meaningOfLife(); ?> 


6. Global Keyword Examples
<?php 
$num_of_calls = 0; 
function numberedHeading( $txt ) 

global $num_of_calls; 
$num_of_calls++; 
print "<h1>$num_of_calls. $txt</h1>"; 

numberedHeading("Widgets"); 
print "<p>We build a fine range of widgets</p>";
 numberedHeading("Doodads"); 
print "<p>Finest in the world</p>"; 
?> 


7. Static Keyword
<?php 
function numberedHeading( $txt ) 
{
static $num_of_calls = 0; 
$num_of_calls++; 
print "<h1>$num_of_calls. $txt</h1>"; 

numberedHeading( "Widgets" ); 
print "<p>We build a fine range of widgets</p>"; 
numberedHeading( "Doodads" ); 
print "<p>Finest in the world</p>"; 
?>


8. Default Arguments
<?php 
function headingWrap( $txt, $size=3 ) 

print "<h$size>$txt</h$size>";
}
headingWrap("Book title", 1); 
headingWrap("Chapter title",);
headingWrap("Section heading",);
?> 


9. Passing by Value
<?php 
function addFive( $num ) 
{
$num += 5; 
}
$orignum = 10; 
addFive( $orignum ); 
print( $orignum ); 
?> 


10. Passing by Reference
<?php function addFive( &$num ) 
{
$num += 5; 

$orignum = 10;
addFive( $orignum ); 
print( $orignum ); 
?> 


11. Returning References
function &addFive( &$num ) 
{ $num+=5; return $num; } 


$orignum = 10; $retnum = & addFive($orignum ); 
$orignum += 10; 
print($retnum ); // prints 25 


12. Creating Anonymous Functions
<?php 
$my_anon = create_function( '$a, $b', 'return $a+$b;' );
print $my_anon( 3, 9 );
// prints 12
?> 

No comments:

Post a Comment