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.

Chapter 6 describes classes and objects in much more detail, including inheritance,<br />

encapsulation (or the lack thereof), and introspection.<br />

Resources<br />

Many modules provide several functions for dealing with the outside world. For<br />

example, every database extension has at least a function to connect to the database,<br />

a function to send a query to the database, and a function to close the connection to<br />

the database. Because you can have multiple database connections open at once, the<br />

connect function gives you something by which to identify that connection when you<br />

call the query and close functions: a resource.<br />

Resources are really integers under the surface. Their main benefit is that they’re garbage<br />

collected when no longer in use. When the last reference to a resource value<br />

goes away, the extension that created the resource is called to free any memory, close<br />

any connection, etc. for that resource:<br />

$res = database_connect( ); // fictitious function<br />

database_query($res);<br />

$res = "boo"; // database connection automatically closed<br />

The benefit of this automatic cleanup is best seen within functions, when the<br />

resource is assigned to a local variable. When the function ends, the variable’s value<br />

is reclaimed by <strong>PHP</strong>:<br />

function search ( ) {<br />

$res = database_connect( );<br />

$database_query($res);<br />

}<br />

When there are no more references to the resource, it’s automatically shut down.<br />

That said, most extensions provide a specific shutdown or close function, and it’s<br />

considered good style to call that function explicitly when needed rather than to rely<br />

on variable scoping to trigger resource cleanup.<br />

Use the is_resource( ) function to test whether a value is a resource:<br />

NULL<br />

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

// $x is a resource<br />

}<br />

There’s only one value of the NULL data type. That value is available through the<br />

case-insensitive keyword NULL. The NULL value represents a variable that has no value<br />

(similar to Perl’s undef or Python’s None):<br />

$aleph = "beta";<br />

$aleph = null; // variable's value is gone<br />

$aleph = Null; // same<br />

$aleph = NULL; // same<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Data Types | 29

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

Saved successfully!

Ooh no, something went wrong!