05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

You can sort the elements of an array with the various sort functions:<br />

sort($person);<br />

// $person is now array('Crapper', 'Edison', 'Wankel')<br />

asort($creator);<br />

// $creator is now array('Toilet' => 'Crapper',<br />

// 'Light bulb' => 'Edison',<br />

// 'Rotary Engine' => 'Wankel');<br />

Use the is_array( ) function to test whether a value is an array:<br />

if (is_array($x)) {<br />

// $x is an array<br />

}<br />

There are functions for returning the number of items in the array, fetching every<br />

value in the array, and much more. Arrays are described in Chapter 5.<br />

Objects<br />

<strong>PHP</strong> supports object-oriented programming (OOP). OOP promotes clean modular<br />

design, simplifies debugging and maintenance, and assists with code reuse.<br />

Classes are the unit of object-oriented design. A class is a definition of a structure<br />

that contains properties (variables) and methods (functions). Classes are defined<br />

with the class keyword:<br />

class Person {<br />

var $name = '';<br />

function name ($newname = NULL) {<br />

if (! is_null($newname)) {<br />

$this->name = $newname;<br />

}<br />

return $this->name;<br />

}<br />

}<br />

Once a class is defined, any number of objects can be made from it with the new keyword,<br />

and the properties and methods can be accessed with the -> construct:<br />

$ed = new Person;<br />

$ed->name('Edison');<br />

printf("Hello, %s\n", $ed->name);<br />

$tc = new Person;<br />

$tc->name('Crapper');<br />

printf("Look out below %s\n", $tc->name);<br />

Hello, Edison<br />

Look out below Crapper<br />

Use the is_object( ) function to test whether a value is an object:<br />

if (is_object($x)) {<br />

// $x is an object<br />

}<br />

28 | Chapter 2: Language Basics<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!