Not the Da Vinci Code

We'll reproduce the code here and intersperse it with comments. (If you would like an overview of the entire class, now would be a good time to download the code for this chapter from the companion website at http://objectorientedphp.com.)

In order to create a class, use the keyword class and an appropriate name:

class DirectoryItems{ ... }

Braces enclose all the elements of a class, indicated by the ellipsis in the preceding line of code.

We discussed the concept of a class in Chapters 2 and 3, but a bit of repetition here won't be amiss. In its simplest form, a class can simply encapsulate a variety of data types, the way a struct does in C or a type in Visual Basic. This class will encapsulate data types, but it will also contain functions or methods.

Like PHP's built-in classes, we'll use Java-style naming conventions for the class name—not underscores, but uppercase letters for the start of each word, otherwise known as studly caps. We'll use the same naming convention for files that contain class definitions. For example, the file that holds the DirectoryItems class will be called DirectoryItems.php. This naming convention is not a requirement but helps readily identify classes and their files.

The first statement inside the class is the declaration of the variable $filearray. Upon declaration, this variable is initialized as an array.

var $filearray = array();


Note:

Notice the use of the var keyword. This syntax will be replaced in PHP 5, but here it simply denotes an instance variable.


Any variable declared at this level, namely inside the braces that enclose the class but outside any class function, is an instance variable or, as we might also refer to it, a data member. (In most cases, classes contain more than one data member, but one is sufficient for the moment.) Instance variables are sometimes also referred to as properties. The placement of instance variables outside of any function indicates that they have scope throughout the class. Their visibility is not restricted to any specific function—they can be accessed from anywhere within the class. You could say they are global to the class.

The Constructor

Next is a function that bears the same name as the class: the constructor. Constructors are commonly used to initialize data members, and as in Listing 4-1, filenames are added to the instance variable $filearray.

Listing 4-1. The DirectoryItems constructor
function DirectoryItems(❶$directory){
    $d = "";
    if(is_dir($directory)){
        $d = opendir($directory) or die("Couldn't open directory.");
        while(false !== ($f=readdir($d))){
           if(is_file("$directory/$f")){
               $this->❷filearray[] = $f;
           }
        }
        closedir($d);
    }else{
      //error
        die("Must pass in a directory.");
    }
}

Constructors are called whenever an object is created. In Listing 4-1, the constructor accepts, as a parameter, a string variable of ❶ a directory name. Any files contained within this directory are added to $filearray.

Referencing Instance Variables

The only remarkable thing about this code is the unusual syntax required to refer to the instance variable. Variables such as $d and $f, which are local to the constructor, are referenced in the same way as any other PHP variable, but when using ❷ $filearray, we must precede it with $this->.

If you're familiar with other OO languages such as C++ or Java, you'll be familiar with $this, a "pseudo-variable" that identifies what follows as an instance variable. However, unlike those other OO languages, use of $this when referring to an instance variable is not optional in PHP.

So much for the explanation of the syntax of the constructor. The constructor actually performs a fairly simple and straightforward programming task.

Wrapper Methods

The rest of the class is made up of a series of functions. Some of these functions simply enclose or wrap existing array-related functions and are called wrapper functions. These wrapper functions count or sort the list of filenames, but instead of calling them functions, let's use OO terminology and refer to them as methods.


Note:

When declaring the methods of a class you are required to use the keyword function. This can perhaps lead to some confusion. However, throughout we will use the term method to distinguish between a regular function call and the calling a class function.


Again, following the studly caps naming convention, if a method name is a compound word, use lowercase for the first word and uppercase for any subsequent words. Listing 4-2 includes three methods that use built-in PHP array functions.

Listing 4-2. Wrapper methods
function indexOrder(){
    sort($this->filearray);
}
////////////////////////////////////////////////////////////////////
function naturalCaseInsensitiveOrder(){
    natcasesort($this->filearray);
}
////////////////////////////////////////////////////////////////////
function getCount(){
    return count($this->filearray);
}

Finally, add one final method to check that files are all images:

Listing 4-3. A method to select only images
function checkAllImages(){
    $bln = true;
    $extension = "";
    $types = array(❶"jpg", "jpeg", "gif", "png");
    foreach ($this->filearray as $key => $value){
        $extension = substr($value,(strpos($value, ".") + 1));
        $extension = strtolower($extension);
        if(!in_array($extension, $types)){
            $bln = false;
            break;
        }
    }
    return $bln;
}

The checkAllImages method loops through each element in the file array, extracts the extension, and checks that it is one of ❶ the acceptable file types.

In sum, the DirectoryItems class is made up of one data member, a special function called a constructor, and four other functions or methods. As already noted, you should save this file as DirectoryItems.php.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.131.238