Prev | Current Page 276 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

inc.php file at
the top of the relevant script, following the include statement used for Library.inc.php:
include Library.inc.php;
include DataCleaner.inc.php;
You then make some modifications to take advantage of the profanity filter, but
upon loading the application into the browser, you??™re greeted with the following fatal
error message:
210 CHAPTER 7 ?–  ADVANCED OOP FEATURES
Fatal error: Cannot redeclare class Clean
You??™re receiving this error because it??™s not possible to use two classes of the same
name within the same script. Starting with PHP 6, there??™s a simple way to resolve this
issue by using namespaces. All you need to do is assign a namespace to each class. To
do so, you need to make one modification to each file. Open Library.inc.php and
place this line at the top:
namespace Library;
Likewise, open DataCleaner.inc.php and place the following line at the top:
namespace DataCleaner;
You can then begin using the respective Clean classes without fear of name clashes. To
do so, instantiate each class by prefixing it with the namespace, as demonstrated in the
following example:
include "Library.php";
include "Data.php";
// Instantiate the Library's Clean class
$filter = new Library::Clean();
// Instantiate the DataFilter's Clean class
$profanity = new DataFilter::Clean();
// Create a book title
$title = "the idiotic sun also rises";
// Output the title before filtering occurs
printf("Title before filters: %s
", $title);
// Remove profanity from the title
$title = $profanity->RemoveProfanity($title);
printf("Title after Data::Clean: %s
", $title);
CHAPTER 7 ?–  ADVANCED OOP FEATURES 211
// Remove white space and capitalize title
$title = $filter->FilterTitle($title)
printf("Title after Library::Clean: %s
", $title);
?>
Executing this script produces the following output:
Title before filters: the idiotic sun also rises
Title after Data::Clean: the shortsighted sun also rises
Title after Library::Clean: The Shortsighted Sun Also Rises
Be sure to consult the PHP manual before implementing PHP 6??™s namespace feature
into your own applications, as the capabilities and constraints are likely to change
significantly following this book??™s publication.


Pages:
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288