WBP Topic 2 Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

PHP Anonymous Functions

 Anonymous functions (Lambda) are PHP features which we do not use often
but they can be really useful in certain situations like passing a function as
an argument in another function, accessing a variable which is declared
outside the scope of the function etc.

Why would you want to use Lambda?


 Lambda is useful because these are throw away functions that you can use
once. Sometimes you need a function to do job but it’s not so common that
you want to define it as a function but you also don’t want to make it
available as a part of your code. So instead of having a function for that you
can create a Lambda for that and use it once.

Anonymous functions (Lambda)


we can create a regular PHP function like this-

function myRegularFunction(){

//function definition here...

}
When you define a regular function you give it a name(myRegularFunction in this
cases). Now you can refer to this function using function name.For example, you
can call this function like this-

myRegularFunction();
 Anonymous functions are similar to the regular function as they can contain
the same type of code, they accept arguments, return values and all…

The key difference is – as the name implies – anonymous functions have no


name. Here is an example of an anonymous function

function($argument1,$argument2){

//anonymous function definition goes here

};
If you have noticed there are two key difference between a regular function and an
anonymous function.
 There is no function name(between function keyword and the opening
parenthesis() which tells PHP that we are creating an anonymous function.
 There is a semicolon(;) after the function definition. This is because
anonymous functions definitions are expressions whereas regular function
definition is code constructs.

While the above code looks fine but it can not be called because this function
doesn’t have any name. This function cannot be referred anywhere but you can do
a lot of handy things with it-

 You can assign it to a variable and can call it using the variable
name. Even you can store a bunch of different anonymous functions in a
single array.
 You can pass this function to another function as a parameter. This is
known as Callback.
 Return it from within an outer function so that it can access the outer
function’s variables. This is known as a closure.

 Assigning anonymous function to variables


 While creating an anonymous function, it can also be assigned to a variable
just like any other value. Here is an example-

$addition=function($arg1,$arg2){

return 'sum = '.$arg1+$arg2;


};
 once you have done that you can call this function with a variable name like-

echo $addition(20,50);
 the output will be

sum = 70
 Or even we can store multiple anonymous functions to an array like this-

//storing 5 anonymous function to an array

$myarray = array(

function(){ echo "this is 0th index function"; },


function(){ echo "this is 1st index function"; },
function(){ echo "this is 2nd index function"; },
function(){ echo "this is 3rd index function"; },
function(){ echo "this is 4th index function"; }
);
Now we can decide which function to call at runtime. we can call any function like
this

echo $myarray[3]

//output- this is 3rd index function


 Using anonymous function as callback
One common use of the anonymous function is to create a simple inline callback
function. A callback function is a function that you can pass to another function as
an argument. Once you access your callback function the receiving function can
use it whenever it needs to.

 Many PHP built-in functions accept callback or you can create your own
function which accepts callback function.
 Let’s see some of the built-in function and understand their functionality

Using array_map() function to run a callback function on each element of the


function array_map() function accept a callback function and an array as argument.
It iterates through every element of the array and applies the callback function to
each element. Your callback function needs to return a value which will replace the
array value and array_map return the modified array.

NOTE: array_map() works on a copy of array you pass to it. The Original array
remains untouched.

Here is example-

//without callback function

$num_array = array(1,2,3,4,5);

foreach ($num_array as $key => $value) {

$new_array[]=$value*$value;

print_r($new_array);
this will output-

Array
(
[0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25
)
when we use a regular function a a callback function in array_map()

//with regular callback function

function square($num){

return $num*$num;

$new_array=array_map('square', $num_array);

print_r($new_array);
this will also output the same result.

Using anonymous function as callback

$new_array = array_map(function($num){

return $num*$num;
}, $num_array);

print_r($new_array);
print_r($num_array);
this will output-

Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
as you can see there is no change in $num_array array. its content remained same.

 Creating Closures with anonymous functions


A closure is same as the lambda apart from it can access the variable which is
created outside of its scope or are not in its perimeter.

Confusing… right?

let’s take an example to get it clear-Simple closure example

We are creating a simple closure using an anonymous function:

//define a regular variable

$user='Peter';

//create a closure using anonymous function

$message=function() use ($user){

echo 'hello'. $user;

$message();//output - hello Peter


As you can see above $user variable is defined outside and is not accessible inside
any function but in this case, closure is able to access it because it was declared in
the use clause of the Closure function definition.

If you alter $user variable within closure it will not affect the original value. its
value will still be “Peter”. If you want to alter the original value you can use the
reference to $user as &$user in closure as below

$message=function() use (&$user){

echo 'hello'. $user;

}
Variable functions
 PHP supports the concept of variable functions. This means that if a variable
name has parentheses appended to it, PHP will look for a function with the
same name as whatever the variable evaluates to, and will attempt to execute
it. Among other things, this can be used to implement callbacks, function
tables, and so forth.

 Variable functions won't work with language constructs such


as echo(), print(), unset(), isset(), empty(), include(), require() and the
like. You need to use your own wrapper function to utilize any of these
constructs as variable functions.
Example. Variable function example

<?php

function foo() {

echo "In foo()<br />\n";

function bar($arg = '')

echo "In bar(); argument was '$arg'.<br />\n";

// This is a wrapper function around echo

function echoit($string)

{ echo $string;

$func = 'foo';
$func(); // This calls foo()

$func = 'bar';

$func('test'); // This calls bar()

$func = 'echoit';

$func('test'); // This calls echoit()

?>

You can also call an object's method by using the variable functions feature.

Example 17-15. Variable method example

<?php

class Foo{

function Variable() {

$name = 'Bar';

$this->$name(); // This calls the Bar() method }

function Bar()

{ echo "This is Bar";

}$foo = new Foo();

$funcname = "Variable";

$foo->$funcname(); // This calls $foo->Variable()

?>
Basic Graphics Concepts
 An image is a rectangle of pixels that have various colors. Colors are identified
by their position in the palette, an array of colors. Each entry in the palette has three
separate color values—one for red, one for green, and one for blue. Each value
ranges from 0 (this color not present) to 255 (this color at full intensity).
 Image files are rarely a straightforward dump of the pixels and the palette.
Instead, various file formats (GIF, JPEG, PNG, etc.) have been created that attempt to
compress the data somewhat to make smaller files.
 Different file formats handle image transparency , which controls whether and
how the background shows through the image, in different ways. Some support an
alpha channel, an extra value for every pixel reflecting the transparency at that
point. Others simply designate one entry in the palette as indicating transparency.
 Antialiasing is where pixels at the edge of a shape are moved or recolored to
make a gradual transition between the shape and its background. This prevents the
rough and jagged edges that can make for unappealing images. Some functions that
draw on an image implement antialiasing.
 With 256 possible values for each of red, green, and blue, there are
16,777,216 possible colors for every pixel. Some file formats limit the number of
colors you can have in a palette (e.g., GIF supports no more than 256 colors); others
let you have as many colors as you need. The latter are known as true color formats,
because 24-bit color (8 bits for each of red, green, and blue) gives more hues than
the human eye can distinguish.

Creating and Drawing Images


 For now, let's start with the simplest
possible GD example. Example 9-1 is a
script that generates a black filled square.
The code works with any version of GD that
supports the PNG image format.
 Example . A black square on a white
background (black.php)

 To see the result, simply point your


browser at the black.php PHP page. To
embed this image in a web page, use:
<img src=”black.php”>
The Structure of a Graphics Program
 Most dynamic image-generation programs follow the same basic steps
outlined in Example 9-1.
 You can create a 256-color image with the ImageCreate( ) function, which
returns an image handle:

$image = ImageCreate(width, height);

 All colors used in an image must be allocated with the ImageColorAllocate( )


function. The first color allocated becomes the background color for the image.[4]
[4]This is true only for images with a color palette. True color images created using
ImageCreateTrueColor( ) do not obey this rule.

$color = ImageColorAllocate(image, red, green, blue);

 The arguments are the numeric RGB (red, green, blue) components of the
color. In Example 9-1, we wrote the color values in hexadecimal, to bring the
function call closer to the HTML color representation "#FFFFFF" and "#000000".
 There are many drawing primitives in GD. Example 9-1 uses
ImageFilledRectangle( ), in which you specify the dimensions of the rectangle by
passing the coordinates of the top-left and bottom-right corners:

ImageFilledRectangle(image, tlx, tly, brx, bry, color);

 The next step is to send a Content-Type header to the browser with the
appropriate content type for the kind of image being created. Once that is done, we
call the appropriate output function. The ImageJPEG( ) , ImagePNG( ), and
ImageWBMP( ) functions create JPEG, PNG, and WBMP files from the image,
respectively:

ImageJPEG(image [, filename [, quality ]]);


ImagePNG(image [, filename ]);
ImageWBMP(image [, filename ]);

 If no filename is given, the image is sent to the browser. The quality argument
for JPEGs is a number from 0 (worst-looking) to 10 (best-looking). The lower the
quality, the smaller the JPEG file. The default setting is 7.5.
 In Example 9-1, we set the HTTP header immediately before calling the
output-generating function ImagePNG( ). If, instead, you set the Content-Type at the
very start of the script, any errors that are generated are treated as image data and
the browser displays a broken image icon. Table 9-1 lists the image formats and their
Content-Type values.
 Table 9-1. Content-Type values for image formats

Changing the Output Format


 As you may have deduced, generating an image stream of a different type
requires only two changes to the script: send a different Content-Type and use a
different image-generating function. Example 9-2 shows Example 9-1 modified to
generate a JPEG instead of a PNG image.
 Example 9-2. JPEG version of the black square 9.4.3.

Basic Drawing Functions


 GD has functions for drawing basic points, lines, arcs, rectangles, and
polygons. This section describes the base functions supported by GD 1.x.
 The most basic function is ImageSetPixel( ) , which sets the color of a specified
pixel:

ImageSetPixel(image, x, y, color);
 There are two functions for drawing lines, ImageLine( ) and ImageDashedLine(
):

ImageLine(image, start_x, start_ y, end_x, end_ y, color); ImageDashedLine(image,


start_x, start_ y, end_x, end_ y, color);

 There are two functions for drawing rectangles, one that simply draws the
outline and one that fills the rectangle with the specified color:

ImageRectangle(image, tlx, tly, brx, bry, color); ImageFilledRectangle(image, tlx, tly,


brx, bry, color);

Specify the location and size of the rectangle by passing the coordinates of the top-
left and bottom-right corners.
 You can draw arbitrary polygons with the ImagePolygon( ) and
ImageFilledPolygon( ) functions:

ImagePolygon(image, points, number, color); ImageFilledPolygon(image, points,


number, color);

Both functions take an array of points. This array has two integers (the x and y
coordinates) for each vertex on the polygon. The number argument is the number of
vertices in the array (typically count($points)/2).

 The ImageArc( ) function draws an arc (a portion of an ellipse):

ImageArc(image, center_x, center_ y, width, height, start, end, color);

The ellipse is defined by its center, width, and height (height and width are the same
for a circle). The start and end points of the arc are given as degrees counting
counterclockwise from 3 o'clock. Draw the full ellipse with a start of 0 and an end of
360.
 There are two ways to fill in already-drawn shapes. The ImageFill( ) function
performs a flood fill, changing the color of the pixels starting at the given location.
Any change in pixel color marks the limits of the fill.

The ImageFillToBorder( ) function lets you pass the particular color of the limits of the
fill:

ImageFill(image, x, y, color);
ImageFillToBorder(image, x, y, border_color, color);
Images with Text
 Often it is necessary to add text to images. GD has built-in fonts for this
purpose. Example 9-4 adds some text to our black square image.

 Figure 9-2. The image with text The ImageString( ) function adds text to an
image. Specify the top-left point of the text, as well as the color and the font to use:

ImageString(image, font, x, y, text, color);

Example of Graphics programming


<?php
$im=ImageCreate(200,200);
$white=ImageColorAllocate($im,0,250,0);
$black=ImageColorAllocate($im,250,0,0);
ImageFilledRectangle($im,50,50,150,150,$black);
header('Content-Type:image/png');
ImagePNG($im);
?>
Images with text
<?php
$box=ImageCreate(400,200);
$bgcolor=ImageColorAllocate($box,40,240,140);
$txtcolor=ImageColorAllocate($box,0,0,0);
ImageString($box,4,100,100,"MSBTE.org.in",$txtcolor);
header('Content-Type:image/png');
ImagePNG($box);
?>

Scaling Images
 There are two ways to change the size of an image. The ImageCopyResized( )
function is available in all versions of GD, but its resizing algorithm is crude and may
lead to jagged edges in your new images. The ImageCopyResampled( ) function is
new in GD 2.x and features pixel interpolation to give smooth edges and clarity to
resized images (it is, however, slower than ImageCopyResized( )). Both functions take
the same arguments:

ImageCopyResized(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);
ImageCopyResampled(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);
 The dest and src parameters are image handles. The point (dx,dy) is the point
in the destination image where the region will be copied. The point (sx,sy) is the
upper-left corner of the source image. The sw, sh, dw, and dh parameters give the
width and height of the copy regions in the source and destination.

Dividing the height and the width by 4 instead of 2 produces the output shown in
Figure 9-10.
imagecopyresized
imagecopyresized — Copy and resize part of an image

Description
imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x
, int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $
src_w , int $src_h ) : bool

imagecopyresized() copies a rectangular portion of one image to another


image. dst_image is the destination image, src_image is the source image identifier.

In other words, imagecopyresized() will take a rectangular area from src_image of


width src_w and height src_h at position (src_x,src_y) and place it in a rectangular
area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

If the source and destination coordinates and width and heights differ, appropriate
stretching or shrinking of the image fragment will be performed. The coordinates
refer to the upper left corner. This function can be used to copy regions within the
same image (if dst_image is the same as src_image) but if the regions overlap the
results will be unpredictable.

Parameters
dst_image-Destination image link resource.

src_image-Source image link resource.

dst_x-x-coordinate of destination point.

dst_y-y-coordinate of destination point.

src_x-x-co-ordinate of source point.

src_y-y-coordinate of source point.

dst_w-Destination width.

dst_h-Destination height.

src_w-Source width.

src_h-Source height.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Resizing an image


This example will display the image at half size.

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes


list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width,
$height);

// Output
imagejpeg($thumb);
?>

imagecopyresampled
imagecopyresampled — Copy and resize part of an image with resampling

Description
imagecopyresampled ( resource $dst_image , resource $src_image , int $dst
_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int
$src_w , int $src_h ) : bool

imagecopyresampled() copies a rectangular portion of one image to another image,


smoothly interpolating pixel values so that, in particular, reducing the size of an image
still retains a great deal of clarity.

In other words, imagecopyresampled() will take a rectangular area from src_image of


width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area
of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

If the source and destination coordinates and width and heights differ, appropriate
stretching or shrinking of the image fragment will be performed. The coordinates refer to
the upper left corner. This function can be used to copy regions within the same image
(if dst_image is the same as src_image) but if the regions overlap the results will be
unpredictable.
Parameters
dst_image-Destination image link resource.

src_image-Source image link resource.

dst_x-x-coordinate of destination point.

dst_y-y-coordinate of destination point.

src_x-x-coordinate of source point.

src_y-y-coordinate of source point.

dst_w-Destination width.

dst_h-Destination height.

src_w-Source width.

src_h-Source height.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple example

This example will resample an image to half its original size.

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions


list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $wi
dth, $height);

// Output
imagejpeg($image_p, null, 100);
?>

Example #2 Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.
<?php
// The file
$filename = 'test.jpg';

// Set a maximum height and width


$width = 200;
$height = 200;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions


list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {


$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig
, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>
Creating PDF files
 To get started, you will need to download the FPDF class from the FPDF
Web site and include it in your PHP script like this:

require('fpdf.php');
 Below is an example of how you can generate a simple PDF using FPDF.

We begin by creating a new FPDF object with:

$pdf= new FPDF();


The FPDF constructor can take the following parameters:

|>String orientation (P or L) -- portrait or landscape


|>String unit (pt,mm,cm and in) -- measure unit
|>Mixed format (A3, A4, A5, Letter and Legal) -- format of pages
 Next, we are going to set some document properties:

$pdf->SetAuthor('ABC');
$pdf->SetTitle('FPDF tutorial');

Because we want to use the same font throughout the whole document, we can set
it before we create a page.

$pdf->SetFont('Helvetica','B',20);
$pdf->SetTextColor(50,60,100);

 The SetFont function takes three parameters; the font family, style and size.
We are using Helvetica, Bold and 20 points, which will be applied to the
title of our document. You can either use one of the regular font families or
set up a different one using the AddFont () function.
 With SetTextColor () we are also setting the font colour for the entire
document. The colours can be represented as RGB or grey scale. Here we
are using RGB values.

Now that that's done, let's set up a page for our PDF document.

$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
 You can pass the AddPage () a parameter of "P" or "L" to specify the page
orientation. I've used "P" for portrait. The SetDisplayMode function
determines how the page will be displayed. You can pass it zoom and layout
parameters. Here we're using 100 percent zoom and the viewer's default
layout.
 Now, that we've set up a page, let's insert an image to make it look nicer and
make it a link while we're at it. We'll display the FPDF logo by calling the
Image function and passing it the following parameters -- name of the file,
the dimensions and the URL.

$pdf->Image('logo.png',10,20,33,0,' ','http://www.fpdf.org/');
You could have also inserted the link with:

$pdf->Link(10, 20, 33,33, 'http://www.fpdf.org/');


 Now let's make a title for our document with a border around it.

$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,'FPDF Tutorial',1,0,'C',0);
 The SetXY function sets the position of x and y coordinates, where we want
the title to appear.
 SetDrawColor will set the colour of the border, using RGB values. After
that's done, we call the Cell function to print out a cell rectangle along with
the text of our title.
 We are passing the function the following parameters; width, height, text,
border, ln, align and fill. The border is either 0 for no border or 1 for frame.
For ln we are using the default value 0, "C" to centre align the text inside it
and 0 for fill. Had we used 1 for fill the rectangle would have been coloured
in. With a value of 0 we are making it transparent.
 Now we want to write the main text to the PDF, that is display a little
message.

$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,'Congratulations! You have generated a PDF. ');
 Again we are setting the x and y positions of the text, but this time we are
reducing the font size with the SetFontSize function. The write function will
print the text to a PDF. The parameter 5 will set the line height. This is only
relevant however, if there are multiple lines of text.
 Finally we want to send the output to a given destination, using the Output
function.

$pdf->Output('example1.pdf','I');
 Here we are passing the function the name of the file and the destination, in
this case "I". The "I" parameter will send the output to the browser.
Example
<?php
require(‘./fpdf.php’);

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

You might also like