Modular Programming - Learn PHP 7: Object-Oriented Modular Programming using HTML5, CSS3, JavaScript, XML, JSON, and MySQL (2016)

Learn PHP 7: Object-Oriented Modular Programming using HTML5, CSS3, JavaScript, XML, JSON, and MySQL (2016)

Chapter 3. Modular Programming

Steve Prettyman1

(1)

Georgia, USA

Electronic supplementary material

The online version of this chapter (doi:10.1007/978-1-4842-1730-6_3) contains supplementary material, which is available to authorized users.

“Yes, I am a terrible coder, but I am probably still better than you :)”

—Rasmus Lerdorf

Chapter Objectives/Student Learning Outcomes

After completing this chapter, the student will be able to:

· Create an error-free simple objected-oriented (OO) modular PHP program

· Create a PHP class and make an instance of the class (object)

· Create an OO PHP encapsulated program, including GET and SET methods

· Create PHP methods (functions) that accept parameters and return information

· Create PHP public and private properties (variables)

· Import existing PHP code from another file or library into a program

· Validate information received using ternary (conditional) operators

PHP Libraries, Extensions, Classes, and Objects

One of the strengths of PHP is the ability to easily store modules of code in libraries. Once code has been installed in a library it can easily be reused in other programs. The reuse of code that has already been well tested and used in “live” environments greatly reduces program errors and increases productivity because you don’t have to reinvent the wheel. There is no need to recreate code that is already successfully working. It’s a waste of time and energy and likely to cause unnecessary program errors. The programmer actually may not know what actual code exists in a module of code (class). However, the programmer knows what parameters (such as numbers) can be passed into the “black box” and what is returned (sum of the numbers) from the black box.

It may concern you that the programmer blindly passes information into the black box and blindly receives information back. However, this is an advantage, not a disadvantage. This allows the creator of the module to update the code without affecting the way the module is used. As long as the module accepts the same input and returns the same output, the programmer who is using the module notices no changes. Updates can occur to the module for better efficiently, better security, or to correct any program code problems without causing the users to change how they handle the module in their code.

PHP Extensions

Example 3-1. Extensions in the php.ini file

extension=php_bz2.dll

extension=php_curl.dll

;extension=php_fileinfo.dll

extension=php_gd2.dll

;extension=php_gettext.dll

;extension=php_gmp.dll

;extension=php_intl.dll

;extension=php_imap.dll

;extension=php_interbase.dll

;extension=php_ldap.dll

extension=php_mbstring.dll

;extension=php_exif.dll

extension=php_mysql.dll

extension=php_mysqli.dll

;extension=php_oci8.dll

For a complete list and explanation of PHP extensions, visit:

http://php.net/manual/en/extensions.alphabetical.php .

PHP has a large amount of libraries available with thousands of lines of well tested code. Example 3-1 is a partial copy of the php.ini file showing several extensions (libraries) that are available to be activated in PHP. Each of these libraries is C code with a PHP wrapper (for better communication with PHP programs). The code is already compiled (notice the .dll extensions). A library that exists in the PHP environment can be activated by removing the comment symbol (;) in front of the extension statement in the php.ini file. Once the INI file has been saved, PHP and Apache must be reloaded (see Chapter 1 for examples on the location of the php.ini file and reloading PHP and Apache). This ease of adding libraries is one of the reasons PHP has become so popular. Additional libraries can be “installed” into PHP using several methods. One of the more popular methods, Pear (PHP Extension and Application Repository), handles code distribution and maintenance of third-party libraries.

The use of Pear and other third-party library installation methods is beyond the scope of this book. However, you can find additional information at the link below.

http://pear.php.net/manual/en/about.pear.php .

In addition, programmers can “install” their own libraries of code (that are not already compiled) directly into an application via the require or require_once statement. It is common practice in corporations to include code that may be reused many times (such as accessing a database). By providing this (well tested) code in a local library, any changes (such as the movement of the database to another server) can be handled in one location (the local library file), instead of requiring multiple files to be changed. This also reduces code redundancy and increases its reliability.

While local libraries can contain just methods (functions) of code, it is more common that modules (classes) exist in these libraries. This allows programmers to code with the “black box” concept previously mentioned. The three-tier architecture (explained in Chapter 2) is based on this premise. The code classes can be accessed from the library by referencing the library containing the code (via the require or require_once statement). Once a reference is made, an instance of the class (object) is then created. Once an instance has been created, the program code has access to all the functionality of the object.

Classes and Objects

A class is similar to a blueprint of a house. The blueprint contains a description (characteristics) of all the elements needed to construct the house. However, the blueprint is not the actual house itself. It describes what is possible if we hire a crew and construct the house. The blueprint is not considered to exist (as a house would exist). However, it describes the items needed to build the house (nails, drywall, and wood) and the process to build the house.

A class describes the characteristics (properties) of the module of code and the actions (methods or functions) that can occur in that code. However, it does not physically exist (within memory) until an instance of the class (called an object) is created. Once an instance is created, the characteristics and methods can be accessed. Classes and objects (when created properly) protect the characteristics (properties) from direct access. This provides the object the opportunity to verify that any request to change a value in a property is valid before the change occurs. This is commonly called encapsulation. To protect properties from direct access to the outside world, they should be declared using the private access type. Private access will only allow methods within the class the ability to change the values in the properties. Set methods (discussed later in this chapter) are used to change properties. Get methods (also discussed later in this chapter) are normally used to retrieve property values.

Creating a PHP Class

Let’s begin by creating a basic structure for a class. You will create a dog class which will allow you to set some characters of the dog (size, breed, color, and name) and you will provide the ability for the dog to speak and to display the values saved in each property. You will create the dog class in a separate file (library) that can be loaded into the program (or any other program) when needed.

To create a PHP class, you use the class keyword and encapsulate all code within the class in {}.

Example 3-2. Basic class structure in the dog.php file

<?php

class Dog

{

// all code is placed here

}

?>

As seen in Example 3-2, the class keyword is lowercase. However, the name of the class, Dog, begins with an uppercase letter. PHP will allow you to create a class with a lowercase first letter. However, it is common practice to easily identify classes by the use of the uppercase first letter. The actual file name containing your class (dog.php) should also match the class name (Dog).

For more information on classes, methods, and properties visit php.net at:

http://php.net/manual/en/classobj.examples.php .

For videos, visit "the new boston" at:

https://www.thenewboston.com/videos.php?cat=11&video=17175 .

Class names cannot include spaces. You should also avoid using special characters. However, the _ is permitted and commonly used to connect two words together (set_name). You many notice that some class names include two underscores (__) before the actual class name (__Myclass). However, this is not a recommended technique due to the existence of “magical” classes (we will look at two of these classes later in this chapter) that use this format.

As mentioned previously, a class contains properties. Properties are also called variables. Properties include characteristics of the class. When an instance of a class is created, the properties are unique for that object. The operating system reserves a space in memory to hold the properties. The operating system handles memory management for us, including cleaning up properties that are no longer needed. In PHP, anytime a closing bracket (}) is reached, properties that have been created are scheduled for removal by the garbage collector of the operating system. The program can no longer access the property at that point.

Properties can hold many different types of data. In most languages, when a property is created you must also include a data type to describe the kind of data being stored (such as string). However, PHP does not require the defining of a data type. PHP determines the type of data to be stored in a property the first time data is placed in the property. Properties are created with an initial $ and the name of the property. Property names can include alphabetic characters, numbers, and the _. The _ can be used at the beginning of the property (after the $) or between words. No spaces are allowed. Properties are commonly created with lowercase letters. However, PHP does allow uppercase letters. PHP is case-sensitive and will consider a lowercase property (speak) and an uppercase property (Speak) two different properties.

Example 3-3. Basic class structure with properties in dog.php file

<?php

class Dog

{

private $dog_size = 0;

private $dog_breed = "no breed";

private $dog_color = "no color";

private $dog_name = "no name";

}

?>

Program design recommendation—Properties are created on the fly in PHP. Properties are created the first time you use them. This can both be a help and a pain. If you misspell a property name, PHP will not produce an error. Instead it will create a new property with the misspelled name. It is recommended (when possible) that properties be created with initial values at the top of your program (or method, or class) to more easily determine what your property name is and whether it has been created.

As seen in Example 3-3, each of the properties (except $dog_size) for the Dog class has been declared private and initially set with a string (text). The $dog_size property has been set to the number zero (we know it is a number and not a string because there are no "" around the zero). The operating system will store the strings values in the properties ($dog_breed, $dog_color, and $dog_name) in ASCII format (combinations of zeros and ones to represent each character) and will store the value in the $dog_size property in a numerical format in memory. The operating system creates memory tables to look up the actual memory address of the value in a variable when it is used in a program.

Note

The format of the code must also include a semicolon at the end of the code statements (all code lines that are executed must include semicolons).

As you may note, at this point the example is not very useful. Even if you were to create an instance of the class, you could not access anything in the class or display the values in the properties. Let’s add a method to the class to allow you to display what is contained in the class. To do so, you need to create a method to display the values using the print statement. You can also take this opportunity to build one single string of output using string concatenation.

String concatenation can be done in several ways in PHP. In many languages, building strings with properties require continuously opening and closing a string (using "").

print "Dog_weight is " . $this->dog_weight . ". Dog breed is " . $this->dog_breed . "Dog color is " . $this->dog_color;

The print code line above is valid in PHP. However, as you can see, you have a lot of quotes and many periods. It can be difficult to get everything matched up correctly. The period is a string concatenation character in PHP and would be required, if you choose to use this technique (you would have to use a similar madness in many languages). However, PHP is much friendlier than this.

This pointer—The $this pointer is used to gain access to properties contained in an object. this indicates that the code wants to retrieve the value contained in a property that exists in the particular object (instance of the class). Soon we will be creating an instance of the class named$lab . When the code that will exist in the $lab instance is executed, the $this pointer will tell the operating system that it wants the value in the property (such as dog_weight ) that exists in the $lab instance only. Note that the format of the statement includes a $ sign for the $this pointer but not for the variable ( $this->dog_weight ).

You might ask, why do we need the $this pointer? The simple answer is that you can create a property that exists for every instance of the class (called a static property). If this type of property changed, it would change for all the instances of the class. Our private properties only change for the particular instance ( $lab ) of the class in which it was referenced.

print "Dog weight is $this->dog_weight. Dog breed is $this->dog_breed. Dog color is $this->dog_color.";

PHP allows you to place properties within strings (quotes). This allows you to use fewer periods and quotes (and maybe reduce pulling too many hairs from your head).

For examples of the $this pointer, visit:

http://php.net/manual/en/language.oop5.basic.php

For videos of the $this pointer, visit:

https://www.thenewboston.com/videos.php?cat=11&video=17177

Now that you have the code needed to produce an output, you need to add a method in the class to execute the print line. All “actions” that take place in a class must be included in a method. Methods are created in a similar style as classes (except they are actually contained within the classes). Methods are declared using the keyword function followed by a method name and (). It is common practice for method names to be lowercase, although PHP will accept uppercase characters. The _ can also be included at the beginning or within the method name. All code with a method is contained within {}.

Example 3-4. Basic class structure with properties and a method in dog.php file

<?php

class Dog

{

private $dog_weight = 0;

private $dog_breed = "no breed";

private $dog_color = "no color";

private $dog_name = "no name";

function display_properties()

{

print "Dog weight is $this->dog_weight. Dog breed is $this->dog_breed. Dog color is $this->dog_color.";

}

}

?>

Program design recommendation—As seen in Example 3-4 , it becomes much more important to be aware of the proper use of the opening and closing brackets ({ and }). For every open bracket, there must be a closing bracket. It can become difficult to determine if you are missing something. Editors (discussed in Chapter 1 ) can help color code everything to make it easier to see. Also, indenting (as seen in Example 3-4 ) can help visually line up the brackets. The PHP engine ignores extra spacing (called whitespace). So the programmer can make the code more visually pleasing and easier to debug.

This class now has the ability to perform an action (via the display_properties method). So you can finally test its functionality. In order to do so, the code from Example 3-4 must be placed in the dog.php file (same as the class name) in the same location as the program that will use it.

We now need to create a program that will pull in this library (via the require_once statement). The program will then need to make an instance of the class (Dog). Finally, the program will need to call the method (display_properties) to display the contents of the properties.

Program design recommendation—PHP will allow the include, include_once, require, and require_once statements to be used anywhere in your program code. This could cause potential issues if it’s used in the incorrect location or used more than once. It is strongly recommended that these statements be include together as close to the top of your code as possible for easy review to determine if libraries have already been installed.

Security and reliability—PHP has several methods available to pull libraries into PHP programs. The include method will attempt to pull in a library. However, if the library does not exist, the program will continue to run (or crash). The include method also does not concern itself with possibility that the library might already have been attached to the code. It is possible that a large program might accidentally try to pull in the same library more than once (which would crash the program due to duplicate method and/or class names). The include_once method eliminates the possibility of attempting to pull in a library more than once. If the library has already been included, the statement will not execute. The require method does not allow the program to continue running if the library cannot be found. However, like the include method, it could attempt to pull in the same library more than once. The require_once method solves these potential problems by shutting the program down if the library cannot be found and by only installing the library if it has not already been installed.

The format of the require_once statement is simple. The keyword require_once is followed with the library name (dog.php). The statement should be included near the top of your code and before you make an actual instance of the class (Dog).

require_once("dog.php");

You can include path names within a require_once statement. However, it is recommended that you do not include absolute paths. For more information visit:

http://php.net/manual/en/function.require-once.php

For Examples visit:

https://www.thenewboston.com/videos.php?cat=11&video=17028

For videos visit:

https://www.thenewboston.com/videos.php?cat=11&video=17029.

To create an instance of a class, a property is created that “points” to the instance of the class in memory. The new keyword is included to inform the operating system that an instance of the class should be created in memory (and the constructor method should execute, as mentioned later). The actual class name is included to determine which class is to be built into an object.

$lab = new Dog;

This code would create an instance of the Dog class and refer to it with the $lab property (pointer). Actual individual copies of each of the properties ($dog_size, $dog_breed, $dog_color, and $dog_name) are created for each instance of a class. This allows you to change what is in the properties for that instance ($lab) without changing the properties for other.

$lab->display_properties();

Once the instance is created, you can then access any methods by using the object name ($lab) and the method name (display_properties).

Example 3-5. Basic program structure including a library, object, and method call in lab.php

<?php

require_once('dog.php');

$lab = new Dog;

$lab->display_properties();

?>

Figure 3-1 shows the successful output of the lab.php program, which includes the Dog class contained in the dog.php file.

A978-1-4842-1730-6_3_Fig1_HTML.jpg

Figure 3-1.

Output of lab.php

For more examples on creating an object (instance of a class), visit: Examples:

http://php.net/manual/en/language.oop5.basic.php

Videos: https://www.thenewboston.com/videos.php?cat=11&video=17181.

Do It

1.

Add a speak method to the Dog class to give each instance the ability to “bark”. Hint: Include a print (or echo) statement in your method. Add a call to your speak method after the call to the display_properties method in the lab.php file.

2.

Create a second object from the Dog class in the lab.php file called $chow. Call the speak method (#1) to make him “bark”.

3.

Create a new library file that contains a class of another animal of your choice. Within that class, create four properties that provide characteristics of that animal. Include a method that will print each of these characteristics. Also include a method that will cause the animal to speak. Create another file that will use this library file to create an instance of the class. The program should also call the method to display the properties and the method to cause the animal to speak.

Program errors—If you encountered errors when trying this example, check the following:

1.

Did you name the class ( Dog ) and the file name ( dog.php ) the same? Make sure the file ending is .php and not .txt for both the dog.php and lab.php files.

2.

In the require_once statement in the lab.php file, is the file name exactly the same as the dog.php file?

3.

Are the dog.php and lab.php files in the same folder?

4.

Did you include the same amount of opening ({) and closing (}) brackets in both programs?

5.

Did you forget any semicolons (;)?

6.

For each $thi s statement, make sure the $ is part of this and not of the property ( $this->dog_weight).

7.

For any other errors, copy and paste your error into a search engine to find possible solutions. Remember, the error may be in either the Apache or PHP error logs (see Chapter 1 for details).

Return Method

In Chapter 2, the business rules tier was defined to contain modules of code that return information requested, but do not provide an interface or format for displaying the data returned. In the previous example, the Dog class violates this requirement. However, you can fix this problem with just a few code changes to the dog.php and lab.php files.

The print statement in the Dog class should be replaced. However, you want to pass multiple values (dog_weight, dog_color, dog_breed, and dog_name) back to the program that has called it. There are many ways that you can accomplish this task. However, since you are just starting programming, let’s keep it simple. We can create a comma-delimitated string easily by reformatting the original string. You can replace the print statement with

Return "$this->dog_weight, $this->dog_breed, $this->dog_color.";

The new Dog class would now contain what’s shown in Example 3-6.

Example 3-6. Basic Dog class with return statement—dog.php

<?php

class Dog

{

private $dog_weight = 0;

private $dog_breed = "no breed";

private $dog_color = "no color";

private $dog_name = "no name";

function get_properties()

{

return "$this->dog_weight,$this->dog_breed,$this->dog_color.";

}

}

?>

Note

In PHP 7, you can enable Scalar Type Hints. PHP 7 provides the developer the ability to declare the data type that is expected to be returned. The function in Example 3-6 could be coded as follows.

declare(strict_types=1);

function get_properties() : string

{

return "$this->dog_weight,$this->dog_breed,$this->dog_color.";

}

If the declare statement is not included or strict_types=0, the data type will not be enforced. The current valid data types that can be used are string, int, float, and bool.

Since Scalar Type Hints are not backward compatable, they are not used in the examples in this book.

You now need to adjust the lab.php file to be able to accept what has been passed back from the get_properties method (display_properties is renamed get_properties to reflect that it no longer displays the properties; it now returns them). You can accomplish this by creating a property in the lab.php file to receive what has been passed back from the get_properties method.

$dog_properties = $lab->get_properties();

If you were to use the print function to display $dog_properties at this point, you would display:

no weight, no breed, no color

However, we intended to produce a similar result as was shown previously. You can do this, but you need to be able to break the string into three pieces based on the “,” delimiter. Luckily there are PHP methods available that can easily accomplish this task. The explode method will break a string based on a delimiter. The substrings (pieces of the string) can then be dropped into individual properties using a list object. For our needs, you can split the $dog_properties string as follows.

list($dog_weight, $dog_breed, $dog_color) = explode(',', $dog_properties);

For more information on the explode function, visit:

http://php.net/manual/en/function.explode.php

This will drop no weight into $dog_weight, no breed into $dog_breed, and no color into $dog_color. These three properties are also being created inside the lab.php program in this same line of code. I happen to give them the same names as their counterparts in the Dog class. However, remember if you had not created the Dog class, you would not know the original variable names. It would not matter, because you can call them anything you want and accomplish the same task.

Now that you have the variables containing the information, you can recreate the original print statement in the lab.php program instead of in the dog.php library.

print "Dog weight is $dog_weight. Dog breed is $dog_breed. Dog color is $dog_color.";

Notice that you did not include the $this pointer. You are not executing this statement within a class. You don’t create instances of the lab.php program. There is only one instance of the program (because it is not a class and cannot have multiple instances). So the $this pointer is unnecessary.

The new lab.php program would now look like Example 3-7.

Example 3-7. The lab.php program with print statement

<?php

require_once("dog.php");

$lab = new Dog;

$dog_properties = $lab->get_properties();

list($dog_weight, $dog_breed, $dog_color) = explode(',', $dog_properties);

print "Dog weight is $dog_weight. Dog breed is $dog_breed. Dog color is $dog_color.";

?>

Assuming there are no errors in your program, the output will be the same as Figure 3-1, unchanged from the previous version of the program. However, the Dog class now meets one of the standards of the business rules tier by returning information to the program that calls it without attempting to format the output. The lab.php program now handles formatting the output.

Do It

1.

Adjust the speak method in the dog.php file to return the bark string but not print it. Also adjust the call to the method in the lab.php file to display the output of the string. You can accept the string from the method and print the string in one line of code using syntax similar to the following:

print $lab->speak();

2.

Adjust the $chow object in the lab.php file to properly handle the return of the properties string and the speak string.

3.

Adjust the animal class to return any strings instead of printing them. Adjust the program that makes an instance of the animal class to accept and display the strings that are returned.

Set Methods

This example is still very limited because you can’t currently adjust the values in the properties to relate to the actual objects you created (such as $lab). In order to adjust these properties, you must have some ability to access the properties from the program that uses the object (lab.php). However, because of encapsulation and security concerns, you do not want to expose the properties to be directly manipulated by the calling program. Object-oriented programming standards require that you create your properties as “private” (as you have done already) and then use actual methods in the class to change any values.

Security and reliability—Creating set methods in classes provides the ability for the class to verify that the information that is to be placed in a property is valid before the property is updated. If this verification is not done before changing the value in a property corruption of data could take place. After the fact, it may be impossible or very difficult to correct invalid data that has been accepted. Set methods can reject invalid data and return error messages to the calling program.

A set method allows values to be passed into the method. These values can then be verified before updating the properties in the object. Parameters (values) are passed into a method between the parentheses () in the method call.

$dog_error_message = $lab->set_dog_name('Fred');

If the set_dog_name method exists within the Dog class and accepts a string representing the name of the dog, you could use a method call similar to the previous code. This call would pass the string "Fred" into the set_dog_name method. It also provides the ability for the set method to return a value into the property $dog_error_message to indicate if the property was updated properly. You can simply pass a ‘TRUE' or ‘FALSE’ Boolean value back from the method to indicate the status of the update. The calling program then can determine how to handle the status of the update.

If you simply pass back a ‘TRUE' or ‘FALSE' you can use a simplified version of the PHP conditional statement, called the ternary operator to check $dog_error_message.

print $dog_error_message == TRUE ? 'Name update successful<br/>' : 'Name update not successful<br/>';

For more information on the ternary conditional operator, visit

http://php.net/manual/en/language.operators.comparison.php

Security and performance—Use caution when display error messages to actual live users of your applications. You can provide too much information and expose your program code unnecessarily. Displaying a generic error message to the user may be a safer option. In live applications, log files should be created to record errors and access to the application itself.

With this format, the calling program (lab.php) can easily determine the status of the update and display a corresponding message. The message between the ? and the : (“Name update successful”) will display if the string in $dog_error_message is ‘TRUE'. If the value in $dog_error_messageis ‘FALSE' the string between the : and the ; (“Name update not successful”) will display.

Example 3-8. The lab.php file with set methods and error checking

<?php

require_once("dog.php");

$lab = new Dog;

// -------------------Set Properties--------------------------

$dog_error_message = $lab->set_dog_name('Fred');

print $dog_error_message == TRUE ? 'Name update successful<br/>' : 'Name update not successful<br/>';

$dog_error_message = $lab->set_dog_weight(50);

print $dog_error_message == TRUE ? 'Weight update successful<br />' : 'Weight update not successful<br />';

$dog_error_message = $lab->set_dog_breed('Lab');

print $dog_error_message == TRUE ? 'Breed update successful<br />' : 'Breed update not successful<br />';

$dog_error_message = $lab->set_dog_color('Yellow');

print $dog_error_message == TRUE ? 'Color update successful<br />' : 'Color update not successful<br />';

//-----------------------------Get Properties---------------------------

$dog_properties = $lab->get_properties();

list($dog_weight, $dog_breed, $dog_color) = explode(',', $dog_properties);

print "Dog weight is $dog_weight. Dog breed is $dog_breed. Dog color is $dog_color.";

?>

In Example 3-8, lab.php now has the ability to pass information into the properties in the $lab object of the Dog class. It also determines if the update for each property was successful and responds accordingly. There are opportunities in this example to be more efficient with the amount of code that you have created. However, we will hold off on efficiency until you have gathered a few more skills.

The lab.php code now calls a set method for each property to be updated (set_dog_name, set_dog_breed, set_dog_weight, and set_dog_color) and passes information into each method. Notice that strings are passed into each method, except for the set_dog_weight method, which accepts an integer (whole number) value.

You now need to create set methods within the Dog class. Each method now accepts a parameter (string or integer) and returns a ‘TRUE' or ‘FALSE' value. The method is created in a style similar to the previous get_properties method that you created. Let’s keep the validation process simple for now and you’ll learn how to improve it in later chapters.

function set_dog_name($value)

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) < 21) ? $this->dog_name = $value : $error_message = FALSE;

return $error_message;

}

The set_dog_name method will accept a string into the $value property (parameter) defined in the function header (function set_dog_name($value)). Next, the method creates a property $error_message and provides an initial value of TRUE. This property (along with the $value property) will only exist while the method is executing. As soon as the execution hits the } closing bracket, these properties will no longer be available.

Programming note— TRUE and FALSE are constants that are included as part of the PHP language. Constants cannot be changed and are in all caps. TRUE is actually represented internally as a 1 and FALSE is represented internally as a 0.

Note

In PHP 7, Scalar Type Hints can be used to enforce the data type being passed and returned.

declare(strict_types = 1);

function set_dog_name(string $value) : string

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) < 21) ? $this->dog_name = $value : $error_message = FALSE;

return $error_message;

}

If the declare line is not included or strict_types = 0, the data type will not be enforced. To allow for backward compatability, the examples in this textbook will not show the use of Scalar Type Hints.

Programming note— && is an AND operator. In order for the ( ctype_alpha($value) && strlen($value) < 21) statement to be TRUE , $value must include only alphabetic characters and must be fewer than 21 characters.

A ternary operator looks at the two possible statuses of the $value property (which contains whatever was passed into the method).

1.

The ctype method is used to determine if the characters in $value are alphabetic (ctype_alpha($value)).

2.

The strlen method is used to determine if the length of the string in $value is less than 21 characters (strlen($value) < 21).

To learn about additional ctype functions, visit: http://php.net/manual/en/book.ctype.php .

If the $value property contains alphabetic characters only and is less than 21 characters, the $dog_name property is updated with the value that has been passed. If there are non-alphabetic characters or the length of the string is more than 20 characters, the $error_message is updated with aFALSE value (indicating the update did not occur). Finally, the value in $error_message (either TRUE or FALSE) is returned to the calling program.

Security and performance—This process may be a bit confusing now. However, it is important to create secure programs. Whenever an application or object accepts information from an outside source (such as another program or user) the information must be validated. This validation should include limitations on the size of the information accepted, along with other restrictions. Data that has been passed across the Internet (such as from the user’s browser to a web server) can be intercepted and changed. It is vital that the information be verified within the application on the server before it is used. Validation may be done in the browser (via JavaScript) to ensure the user has entered correct information. However, as stated, packet stiffing programs can intercept that information and change it before it is received by an application on a web server.

One final note before you look at the code changes. PHP provides several operations to compare two values. The following table provides a summary of these operators, including the new PHP 7 Spaceship Operator.

Operation Result – returns TRUE if...

$a == $b $a and $b are equal ignoring cases

$a === $b $a and $b equal if case is the same

$a != $b, $a <> $b $a and $b are not equal ignoring cases

$a !== $b $a and $b are not equal or not same case

$a < $b $a is less than $b

$a <= $b $a is less than or equal to $b

$a > $b $a is greater than $b

$a >= $b $a is greater than or equal to $b

------------------------------------------------------

(Available with PHP 7) $a <=> $b returns -1 if $a < b, returns 0 if $a equals $b

returns 1 if $a > $b

In addition, the Null Coalesce Operator can be used to check if a value is ‘set’ (contains something) before it is used in a ternary operation.

$dog_name = $_POST['value'] ?? 'No Name';

In this example, if something exists in value, it is placed in $dog_name. If value is not set, No Name is placed in $dog_name. This operator is available in PHP 7. To allow for backward capability, the examples in this book will not demonstrate this operator.

Let’s update the Dog class to include all the set methods needed.

<?php

class Dog

{

// ------------------------------------ Properties -----------------------------------------

private $dog_weight = 0;

private $dog_breed = "no breed";

private $dog_color = "no color";

private $dog_name = "no name";

}

Example 3-9. Dog class with set methods in dog.php

// ------------------------------ Set Methods ----------------------------------------------

function set_dog_name($value)

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) <= 20) ? $this->dog_name = $value : $error_message = FALSE;

return $error_message;

}

function set_dog_weight($value)

{

$error_message = TRUE;

(ctype_digit($value) && ($value > 0 && $value <= 120)) ? $this->dog_weight = $value : $error_message = FALSE;

return $error_message;

}

function set_dog_breed($value)

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) <= 35) ? $this->dog_breed = $value : $error_message = FALSE;

return $error_message;

}

function set_dog_color($value)

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) <= 15) ? $this->dog_color = $value : $error_message = FALSE;

return $error_message;

}

}

function get_properties()

{

return "$this->dog_weight,$this->dog_breed,$this->dog_color.";

}

}

?>

Program design recommendation—When coding and testing your programs, code just one set method. Then test the method to correct errors. After you have one successful set method, copy and paste it in your code and make the necessary changes. Do not attempt to completely code a program before testing it. Program piece by piece, then test. Although you may think that this slows down your coding, actually this is not true. By catching errors with each small addition to your program it will be easier to find them. If you attempt to code a complete program you may have lots of errors and could spend a lot of time trying to hunt down each error. If you are having difficulty finding an error, comment out (using // ) the new lines of code in your program and retest. If all is okay, then gradually (just a few lines at a time) remove the comment lines ( // ) from your code lines and retest. This process should help you to find the lines of code that might be causing problems.

Security and performance—In a live environment the programmer should not display details to the users as to what caused an update to be unsuccessful. Providing too much information can inform hackers on what can be changed to successfully update properties with invalid information. Pass the details of what caused the unsuccessful update to a secure log file on a server.

The code is starting to get lengthy. However, each of the set functions is very similar. As you code the set functions, you will find that this is a common occurrence. It also allows you to quickly create set methods once you have a working error free example by copying and pasting working methods and making simple changes. In Example 3-9 different string lengths are determined depending on the type of information being updated. Also, the $set_dog_weight method checks for numeric values in the string passed, instead of alphabetic characters. Otherwise, the methods are almost identical.

Figure 3-2 demonstrates the output when valid information is passed into each property. The ‘successful’ messages display. Also note that the get_properties method displays the new updated values for each property. In a live environment you might consider not displaying the successful messages and only displaying the not successful messages.

A978-1-4842-1730-6_3_Fig2_HTML.jpg

Figure 3-2.

Output of successful update via set methods in Dog class—dog.php and lab.php

Figure 3-3 tests the output generated when invalid information has been passed to the set methods. Note that the default values are still in the properties that did not get updated. This stresses the need to include default values in case some properties do not get updated. In PHP, properties that are displayed and are NULL (have no value) do normally display a blank space for output. For example, if $dog_weight did not have a default value, the output would display "Dog weight is .".

A978-1-4842-1730-6_3_Fig3_HTML.jpg

Figure 3-3.

Output with invalid weight (1000) and invalid breed (‘Lab12’) in Dog class—dog.php and lab.php

Program design recommendation—Although PHP is friendly and will attempt to change NULL values to spaces when displayed, it is not good programming to assume this will occur. Many program languages will not do this conversion for you and will display error messages when attempting to display properties with NULL values. Also, when using properties to do mathematical calculations, it is very important to set default values. PHP will, again, attempt to convert NULL values to zeros for calculations. However, in some cases this will not occur and an error message will display. In many program languages, error messages will occur when attempting to do a calculation with NULL values. Establishing programming habits that work for all languages will help you quickly develop skills for multiple languages.

Do It

1.

Create an additional property ($dog_gender) in the Dog class. Create a set method (set_dog_gender). Determine if a valid value (Male, Female) has been passed into the set method. You can use the following code or develop your own version to check for valid information.

($value == 'Male' || $value == 'Female') ? $this->dog_gender = $value : $error_message = FALSE;

2.

Go to php.net and search for a method that will allow the checking of any case of “Male” or “Female” from #1. Update the conditional statement to allow any version (Male, MALE, male, Female, FEMALE, female, and so on). Hint: The characters in $value can be changed to all uppercase or all lowercase using the strtoupper or strtolower methods. Then check the string as all uppercase (MALE, FEMALE) or all lowercase (male, female) characters.

Get Methods

In our previous examples, you created a get_properties method that returned multiple properties at the same time. This is a valid and useful method. However, it is common to have a get method to match each set method. This provides both write (set method) and read (get method) capabilities for the properties in a method. In some situations you may want to only provide a get method without a set method (making the property read-only). We could (although rarely done) provide a set method without a get method (making the property write-only).

Get methods are actually much easier to code than set methods. No verification of data is necessary because you are reading the data and not updating it.

function get_dog_name()

{

return $this->dog_name;

}

All that is necessary in the get method is the return statement, which returns the value in the property without the user of the object having direct access to the property.

Example 3-10. Dog class with set and get methods—dog.php

<?php

class Dog

{

// ----------------------------------------- Properties ------------------------------------

private $dog_weight = 0;

private $dog_breed = "no breed";

private $dog_color = "no color";

private $dog_name = "no name";

}

// ---------------------------------- Set Methods ------------------------------------------

function set_dog_name($value)

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) <= 20) ? $this->dog_name = $value : $error_message = FALSE;

return $error_message;

}

function set_dog_weight($value)

{

$error_message = TRUE;

(ctype_digit($value) && ($value > 0 && $value <= 120)) ? $this->dog_weight = $value : $error_message = FALSE;

return $error_message;

}

function set_dog_breed($value)

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) <= 35) ? $this->dog_breed = $value : $error_message = FALSE;

return $error_message;

}

function set_dog_color($value)

{

$error_message = TRUE;

(ctype_alpha($value) && strlen($value) <= 15) ? $this->dog_color = $value : $error_message = FALSE;

return $error_message;

}

// ----------------------------------------- Get Methods -----------------------------------

function get_dog_name()

{

return $this->dog_name;

}

function get_dog_weight()

{

return $this->dog_weight;

}

function get_dog_breed()

{

return $this->dog_breed;

}

function get_dog_color()

{

return $this->dog_color;

}

function get_properties()

{

return "$this->dog_weight,$this->dog_breed,$this->dog_color.";

}

}

?>

The code is lengthy. However, as pointed out previously, like the set methods, the get methods are very similar to each other. Once you have created one successful get method, you can copy and paste it to create the other methods. All that needs to change for each get method is the name of the method and the property being returned.

Example 3-11. The lab.php program using set and get methods

<?php

require_once("dog.php");

$lab = new Dog;

// ------------------------------Set Properties--------------------------

$dog_error_message = $lab->set_dog_name('Fred');

print $dog_error_message == TRUE ? 'Name update successful<br/>' : 'Name update not successful<br/>';

$dog_error_message = $lab->set_dog_weight(50);

print $dog_error_message == TRUE ? 'Weight update successful<br />' : 'Weight update not successful<br />';

$dog_error_message = $lab->set_dog_breed('Lab');

print $dog_error_message == TRUE ? 'Breed update successful<br />' : 'Breed update not successful<br />';

$dog_error_message = $lab->set_dog_color('Yellow');

print $dog_error_message == TRUE ? 'Color update successful<br />' : 'Color update not successful<br />';

// ------------------------------Get Properties--------------------------

print $lab->get_dog_name() . "<br/>";

print $lab->get_dog_weight() . "<br />";

print $lab->get_dog_breed() . "<br />";

print $lab->get_dog_color() . "<br />";

$dog_properties = $lab->get_properties();

list($dog_weight, $dog_breed, $dog_color) = explode(',', $dog_properties);

print "Dog weight is $dog_weight. Dog breed is $dog_breed. Dog color is $dog_color.";

?>

When viewing the code in Example 3-11, note that the print statements call the get methods (print $lab->get_dog_name() . "<br/>";). The order of operations, which will be discussed in more detail in a later chapter, causes the method (get_dog_name()) to be executed first, even though normally a line of code would execute from left to right. The method returns the value in dog_name (the string "Fred"). The string is placed in the same location in which the method call was located. After the get method executes, the code line is now

print "Fred" . "<br/>";

Then the code line executes from left to right, producing the output

Fred <br/>

Programming note—Unlike properties, methods must NOT be included in quotes ("" or ''). The string must be broken apart and concatenated using the '.', as shown in the example. If a method is included IN quotes, PHP will display an error message.

As you can see from Figure 3-4, the get methods successfully display the updated values in the properties. If any properties were not updated, the get methods would display the default values.

A978-1-4842-1730-6_3_Fig4_HTML.jpg

Figure 3-4.

Dog class output with set and get methods

Program design recommendation—While in coding and testing phase it is a good idea to display the values in your properties often to ensure that they are updated at the proper times. However, when you move a program from testing mode to production you should reduce the amount of display shown to the users. It probably is not necessary to show the users the update values in properties. It is usually best to just indicate to the users that the update was successful. You can simply comment out your unneeded print code lines before production. This then could help to quickly debug future upgrades to the application by simply removing comments from those lines.

Do It

1.

In addition to creating an additional property ($dog_gender) and set method in the Dog class, create a get method to display the updated values. Also update the lab.php file to include a print statement (similar to the examples in this section) to call the get methods.

Constructor Method

One difficulty with the previous examples is the amount of calls to set routines that would be required if you are initially creating an object and populating the properties of the object with values. The Dog class requires that you call four set methods (set_dog_name, set_dog_breed,set_dog_color, and set_dog_weight) in order to place values in all the properties. You can use a much more efficient way of updating all these properties at once. This could reduce the code in the lab.php file. You could then use the set routines in the Dog class to make any changes (maybe the dog gained some weight) after you have provided initial values. The initial values are not default values. You still need default values in case the initial values are invalid.

When an instance of a class (object) is created in memory, the operating system executes a constructor method that builds the object with any properties and methods. The system also builds tables in memory to keep track of the location of the object and the values that exist in the properties of the object. When the object is no longer needed, the operating system’s garbage collector will call by the object’s destructor method, which will remove it from memory.

You can also include a constructor method that will automatically be called when the object is placed in memory. When the code line that creates the object ($lab = new Dog;) is executed, it looks for a constructor method in the object. If it exists, the method is executed. You can pass all the initial values for the properties into this constructor method via same line that creates the object.

$lab = new Dog('Fred', 'Lab', 'Yellow', 50);

This becomes a much more efficient way of providing the initial values from within the lab.php program.

The constructor method is a generic format with a function name __ construct (note there are two underscores before the word construct).

<?php

class Dog

{

function __construct($value1, $value2, $value3, $value4)

{

// code to update properties

}

// other methods

}

?>

You can use the existing set methods in the constructor to update the properties. You will need to collect any messages (TRUE/FALSE) and return them to the calling program (lab.php). You can use a similar procedure as you initially coded with the handling of the get_properties method.

Example 3-12. Dog class with constructor—dog.php

<?php

class Dog

{

// ----------------------------------------- Properties ------------------------------------

private $dog_weight = 0;

private $dog_breed = "no breed";

private $dog_color = "no color";

private $dog_name = "no name";

private $error_message = "??";

// ---------------------------------- Constructor ------------------------------------------

function __construct($value1, $value2, $value3, $value4)

{

$name_error = $this->set_dog_name($value1) == TRUE ? 'TRUE,' : 'FALSE,';

$breed_error = $this->set_dog_breed($value2) == TRUE ? 'TRUE,' : 'FALSE,';

$color_error = $this->set_dog_color($value3) == TRUE ? 'TRUE,' : 'FALSE,';

$weight_error= $this->set_dog_weight($value4) == TRUE ? 'TRUE' : 'FALSE';

$this->error_message = $name_error . $breed_error . $color_error . $weight_error;

}

//------------------------------------toString----------------------------------------------

public function __toString()

{

return $this->error_message;

}

//... There are no other code changes to dog.php below this line.

For more information about the __construct method, visit:

Examples: http://php.net/manual/en/language.oop5.decon.php

Videos: https://www.thenewboston.com/videos.php?cat=11&video=17181

First, let’s discuss the use of the special method called __ toString (note the two underscores) in Example 3-12. Constructor methods are not allowed to return information (by default). The return statement cannot be used within the constructor. In order to return error messages created in the constructor to the calling program (lab.php), you must trick the program. The __toString method allows the programmer to decide what will occur if an attempt is made to use the print (or echo) method with the object name (print $lab;). Normally an error message would occur claiming the object cannot be converted to a string (print and echo can only display strings). This can be overridden by including a __toString method with a statement that returns a string. You can overcome this problem of being able to return the error messages by allowing the value in the$error_message property to be returned if the print $lab; statement is executed.

For more information on the __toString method and other magic methods visit

http://php.net/manual/en/language.oop5.magic.php .

The TRUE and FALSE constants that are returned by the set methods also cause a problem because they are constants and not strings. If you attempt to convert these constants to a string using a method (such as strval(TRUE);), the values that they represent (1 for TRUE, 0 for FALSE) would become a string instead of ‘TRUE' or ‘FALSE'. Therefore, they cannot be returned via the __toString method. To overcome this problem we create the following code in the constructor to do a conversion from TRUE to ‘TRUE' or FALSE to ‘FALSE'.

$name_error = $this->set_dog_name($value1) == TRUE ? 'TRUE,' : 'FALSE,';

The order of operations will cause the set_dog_name method to execute before any of part of this code. The set_dog_name method returns TRUE or FALSE (constants). Assuming that the method returns a TRUE after the execution, the code line would now be

$name_error = TRUE == TRUE ? 'TRUE,' : 'FALSE,';

The order of operations then requires that the comparison (TRUE == TRUE) be evaluated. Of course, this evaluates to TRUE. The statements between the ? and the : are used.

$name_error = 'TRUE,';

Thus $name_error is set to the string "TRUE,", which is now a string, not a constant.

Also note that a ‘,’ has been added in preparation for the next ‘TRUE' or ‘FALSE' value. Each value passed (except the last value) must be separated by a ‘,’ to allows the string to be separated later.

The other three similar lines are evaluated and also place a ‘TRUE,’ or ‘FALSE,’ in the error message properties (the weight error evaluation does not include a comma at the end of the string since it is the last one evaluated).

The last line of code in the constructor is evaluated.

$this->error_message = $name_error . $breed_error . $color_error . $weight_error;

This line places the values of each error property into the error_message property. If all the updates were successful, the $error_message property would contain

"TRUE,TRUE,TRUE,TRUE"

Notice that each item passed includes a “,’ for separation except the last item. This is necessary to break apart the results of the string.

Example 3-13. The lab.php file calling a constructor

<?php

require_once("dog.php");

$lab = new Dog('Fred','Lab','Yellow','100');

list($name_error, $breed_error, $color_error, $weight_error) = explode(',', $lab);

print $name_error == 'TRUE' ? 'Name update successful<br/>' : 'Name update not successful<br/>';

print $breed_error == 'TRUE' ? 'Breed update successful<br/>' : 'Breed update not successful<br/>';

print $color_error == 'TRUE' ? 'Color update successful<br/>' : 'Color update not successful<br/>';

print $weight_error == 'TRUE' ? 'Weight update successful<br/>' : 'Weight update not successful<br/>';

// ------------------------------Set Properties--------------------------

...There are no other changes to lab.php below this line.

There is a slight change to the creation of the object on the third line of Example 3-13.

$lab = new Dog('Fred','Lab','Yellow','100');

You are now passing the initial values (Fred, Lab, Yellow,and 100) into the object via the constructor. Otherwise, you would have to make four calls to set methods (set_dog_name, set_dog_breed, set_dog_color, and set_dog_weight) to accomplish the same thing. This allows you to use theset methods for updates that are needed after you have initially set up the object ($lab).

In order to determine if the updates to the four properties were successful, you must retrieve your values (TRUE, TRUE, TRUE,TRUE) from the $error_message property in the object. The __toString method in the Dog class allows you to do this by treating $lab as if it were a string. This allows you to use the explode method in a similar process as the output to the get_properties method.

list($name_error, $breed_error, $color_error, $weight_error) = explode(',', $lab);

This line of code will break the contents of $lab (TRUE, TRUE, TRUE,TRUE) by the commas and place each part into the properties $name_error, $breed_error, $color_error, and $weight_error. Each of these properties will now contain the string 'TRUE'. You can then evaluate your messages to see if the updates were successful in a very similar technique that evaluated the results of the set methods.

print $name_error == 'TRUE' ? 'Name update successful<br/>' : 'Name update not successful<br/>';

There are only a few minor differences between this format and the similar statements to evaluate the results of the set methods. Each of these code lines uses a different error message for evaluation ($name_error, $breed_error, $color_error, and $weight_error). Previously you used the same property ($error_message) for all the results from the set methods. You are now evaluating the string 'TRUE' instead of the constant TRUE (the only difference in the code is the actual quotes).

In Figure 3-5, the first four lines of output are produced from passing values into the constructor to provide initial settings for each property. The next four lines of output are produced when the set methods are used to change the values in the properties. The final four lines are produced from execution of the get methods (showing the contents of each property). The last line of output was produced by the get_properties method. Although the initial values (Fred, Lab, Yellow, and 100) are passed into the constructor successfully, the values in each property were the changed using the set methods (passing Sally, Labrador, Brown, and 5).

A978-1-4842-1730-6_3_Fig5_HTML.jpg

Figure 3-5.

Output from dog.php and lab.php with the constructor, set, and get methods

Security and performance—Some would argue that it’s overkill to check for errors every single time an update occurs. However, in the current environment with constant attempts to corrupt data, it is necessary to be as careful as possible when doing updates. No program is 100% protected from data corruption. Hopefully, you have noticed that once you develop a routine of checking data, your data checking code lines become very similar each time. Thus, by copying and pasting (with minor changes) code lines that successfully verify data, you can greatly increase your security without adding a lot of extra coding time.

Do It

1.

This chapter has covered a lot of PHP examples and terms. To help clarify any difficulties you might currently be experiencing in understanding the PHP language, visit this web site for additional tutorials:

http://www.w3schools.com/php/default.asp

2.

Update the constructor in the Dog class to also allow the passing of the dog_gender value (Male or Female). Update the lab.php program to pass the gender through the constructor. Also update lab.php to explode the $lab string into five parts (one more for the dog_gender). Then evaluate the results ('TRUE' or 'FALSE') returned from the gender_error to display "Gender update successful" or "Gender update not successful".

Chapter Terms

PHP Extensions

Pear

require

require_once

Class

Properties

Variables

Methods

Functions

Object

Encapsulation

Private

set Method

get Method

$this Pointer

String Concatenation

Include

include_once

new Keyword

return

Comma-Delimitated String

explode Method

Substrings

set Method

Boolean Value

Conditional Statement

Ternary Operator

Integer

Parameter

Null Coalesce Operator

&&, And

ctype_alpha

strlen

ctype_digit

||, Or

Spaceship Operator

NULL

Order of Operations

Constructor Method

Destructor method

__toString

List object

Chapter Questions and Projects

Multiple Choice

1.

PHP variables begin with which symbol?

a.

?

b.

!

c.

$

d.

&

2.

A valid function name can start with which of the following?

a.

A letter

b.

An underscore

c.

A number

d.

Both A and B

3.

Which conditional statement syntax is valid for PHP?

a.

IF (condition) { execution };

b.

IF (condition) { execution }

c.

if (condition) { execution };

d.

if (condition) {execution}

4.

Which of the following includes properties and actions (methods or functions) that can occur in an application?

a.

Class

b.

set method

c.

get method

d.

for loop

5.

Which basic function does a constructor method perform?

a.

Defines properties

b.

Defines methods

c.

Places an instance of a class into memory

d.

A and B

6.

The && symbol and/or the word AND

a.

Are relational operators, when used, and require all statements checked to be true for the complete if statement to be considered true

b.

Are conjunctions used in PHP to connect programs

c.

Are relational operators, when used, and require that only one statement checked to be true for the complete if statement to be considered true

d.

Are relational operators and conjunctions used in PHP to connect programs

7.

An integer is which of the following?

a.

A string or text value

b.

A floating-point number

c.

A whole number

d.

A fraction

8.

A ternary operator is which of the following?

a.

An alternative to setting a variable

b.

An alternative to using an if-else conditional statement

c.

An alternative to using an embedded if-else conditional statement

d.

B and C

9.

How does one create an instance of the class fred and execute the constructor method in PHP?

a.

$this->fred

b.

$variable = new fred

c.

$load_class = fred

d.

$fred

10.

What purpose does the method ctype_digit serve?

a.

Randomly generates an integer value

b.

Determines whether characters inputted are numeric

c.

Determines whether a class output is numeric

d.

Converts a string value to an integer

11.

Pear is an acronym for

a.

PHP Extends and Applies Registry

b.

PHP Excellence in Applied Requirements

c.

PHP Extension and Application Repository

d.

Properties of Extension and Application Registry

12.

Creating set methods inside classes

a.

Allows properties to be changed automatically

b.

Should not be done as it corrupts data

c.

Provides the ability for the class to verify information before the property is updated

d.

Provides the ability for the class to verify information after the property is updated

13.

if statements

a.

Are also called conditional statements

b.

Can compare two values to determine if they are the same or different

c.

Use comparison operators (==, <, >, <=, >=) to determine if the statement is true or false

d.

All of the above

14.

$x && $y condition is TRUE if

a.

Both $x and $y are true

b.

$x or $y are true

c.

Both $x and $y are false

d.

$x or $y are false

15.

Select the statement about Boolean values that is false.

a.

Boolean is a data type having two possible values—TRUE and FALSE

b.

Boolean values represent the truth values of logic

c.

Boolean values are only associated with conditional statements

d.

In PHP Boolean literals, TRUE and FALSE are case-sensitive

16.

Which one of these numbers is an example of an integer?

a.

1.01

b.

2f

c.

423

d.

.002

17.

Protecting an object’s data from code outside the class is called what?

a.

Inheritance

b.

Encapsulation

c.

Classification

d.

Blocking

18.

Which kind of methods are easier to code than set methods and are known as read only methods since they do not change any property values?

a.

explode methods

b.

get methods

c.

constructor methods

d.

match methods

19.

Why would you include objects in your program?

a.

To make notes in your code

b.

To make mini mobile programs

c.

To make your code more complex

d.

To protect your code from direct access

20.

How do you call a function named myFunction?

a.

call myFunction();

b.

myFunction();

c.

call function myFunction;

d.

call.myFunction();

21.

A class can contain all of the following except

a.

Properties

b.

Methods or functions

c.

Conditional statements

d.

Machine code

22.

When working with a comma-delimited string, which character is used to separate the data in the string?

a.

Space

b.

Semicolon

c.

Asterisk

d.

Comma

True/False

1.

Methods are functions that belong to a class.

2.

You would use the symbol || or the word or when you want both conditions to be true.

3.

When a function is private, it can only be used inside the class in which it exists.

4.

The explode method can be used to separate a string at the specified delimiter.

5.

The new keyword tells the operating system that an instance of that class should be created in memory.

6.

The function Ctype_alpha will return true when a number is passed into it.

7.

require_once will not execute if the file has already been attached to the program.

8.

The ctype_digit function determines if the characters passed are alphabetic.

9.

The ctype_alpha function determines if the characters passed are alphabetic.

10.

A PHP constructor has the same name as the class.

11.

A ternary operator is shorthand for a while loop.

12.

If a file has already been included in a program, the require_once function will generate only a warning and allow the program to continue.

13.

Destructor methods are called when there are no remaining references to an object or when that object has been explicitly destroyed.

14.

Objects are blocks of code that have already been compiled for use in an application.

15.

The else statement extends an if statement by allowing code to execute when the if statement evaluates to FALSE.

16.

include or require statements can only be placed at the top of an PHP program.

17.

Programmers can pull their own libraries of code into an application via the require or require_once statement.

Short Answer/Essay

1.

Explain the meaning of encapsulation and how classes are encapsulated.

2.

Why should a programmer use set and get methods?

3.

Why should every entry on a web page from a user be validated?

Projects

1.

Create a PHP program with a class (Student) with the following properties: student_id, student_name, student_address, student_state, student_zip, and student_age. The program includes get and set methods for each property. Validate the proper type and size of data passed into each property. The program also includes the ability for each property to use the constructor to set values. Create an instance of the class passing properties through the constructor. Change two of the properties using set methods. Display the properties using get methods.

2.

Create a PHP program to keep track of inventory within a grocery store. Each item (class) includes an item number, description, size, self, isle, amount, and price. Each field must be verified for proper information before the entries are accepted. Item numbers range from 00000 to 99999. The store has 16 isles (00-15). No price in the store is greater than $1000. All entries are coded via a constructor or set methods. After all entries have correctly been accepted, the program will generate a report of the entries (using get methods).

Term Project

1.

Using the design from the Chapter 2 Term Project, create a PHP program that will provide the interface for entering in the ABC Computer Parts Corporation inventory items for the warehouse. The PHP class must verify the contents of the information passed from each field (via the setmethods) to ensure that no corruption has taken place. Set and Get methods for each property must exist in the class. The constructor should use the set methods to populate the properties. Also create an interface program that will make an instance of the class and test the ability to populate the properties. The test program should generate a report of the item placed in inventory (similar to the output shown in this chapter). The files created should use logic similar to what was shown in the examples in this chapter.