text
stringlengths
1
7.76k
source
stringlengths
17
81
40. Functions Functions are essential in PHP programming. PHP provides a large library of standard functions to perform basic input/output, math, and many other functions. PHP also provides the ability to define and use your own functions. PHP does not support function overloading, so when you define a function and give it a name, that name cannot be in conflict with any other function name in the standard library or any other code that you might use. Careful thought should go into the design and naming of your functions. PHP supports both call by value and call by reference. As of PHP 5.6, vararg functions are also supported (though earlier versions supported some vararg-like functions such as printf() ). However, we will not go into detail here. Finally, another feature of PHP is that function parameters are all optional. You may invoke a function with a subset of the parameters. Depending on your PHP setup, the interpreter may issue a warning that a parameter was omitted. However, PHP allows you to define default values for optional parameters. 40.1. Defining & Using Functions In general, you can define functions anywhere in your PHP script or codebase. They can even appear after code that invokes them because PHP hoists the function definitions by doing two passes of the script. However, it is good style to include function definitions at the top of your script or in a separate PHP file for organization. 40.1.1. Declaring Functions In PHP, to declare a function you use the keyword function . Because PHP is dynami- cally typed, a function can return any type. Therefore, you do not declare the return type (just as you do not declare a variable’s type). After the function keyword you provide an identifier and parameters as the function signature. Immediately following, you provide the function body enclosed with opening/closing curly brackets. Typically, the documentation for functions is included with its declaration. Consider the following examples. In these examples we use a commenting style known as “doc comments.” This style was originally developed for Java but has since been adopted by many other languages. 535
ComputerScienceOne_Page_569_Chunk2101
40. Functions 1 /** 2 * Computes the sum of the two arguments. 3 */ 4 function sum($a, $b) { 5 return ($a + $b); 6 } 7 8 /** 9 * Computes the Euclidean distance between the 2-D points, 10 * (x1,y1) and (x2,y2). 11 */ 12 function getDistance($x1, $y1, $x2, $y2) { 13 $xDiff = ($x1-$x2); 14 $yDiff = ($y1-$y2); 15 return sqrt( $xDiff * $xDiff + $yDiff * $yDiff); 16 } 17 18 /** 19 * Computes a monthly payment for a loan with the given 20 * principle at the given APR (annual percentage rate) which 21 * is to be repaid over the given number of terms (usually 22 * months). 23 */ 24 function getMonthlyPayment($principle, $apr, $terms) { 25 $rate = ($apr / 12.0); 26 $payment = ($principle * $rate) / (1-pow(1+$rate, -$terms)); 27 return $payment; 28 } Function identifiers (names) follow similar naming rules as variables, however they do not begin with a dollar sign. Function names must begin with an alphabetic character and may contain alphanumeric characters as well as underscores. However, using modern coding conventions we usually name functions using lower camel casing. Another quirk of PHP is that function names are case insensitive. Though we declared a function, getDistance() above, it could be invoked with either getdistance() , GETDISTANCE or any other combination of uppercase/lowercase letters. However, good code will use consistent naming and your function calls should match their declaration. The keyword return is used to specify the value that is returned to the calling function. Whatever value you end up returning is the return type of the function. Since you do not specify variable or return types, functions are usually referred to as returning a “mixed” type. You could design a function that, given one set of inputs, returns a number while another set of inputs returns a string. You can use the syntax return; to return no 536
ComputerScienceOne_Page_570_Chunk2102
40.1. Defining & Using Functions value (you do not use the keyword void ). In practice, however, the function ends up returning null when doing this. 40.1.2. Organizing Functions There are many coding standards that guide how PHP code should be organized. We’ll only discuss a simple mechanism here. One way to organize functions is to collect functions with similar functionality into separate PHP source files. Suppose the functions above are in a PHP source file named utils.php . We could include them in another source file (our “main” source file) using an include_once function invocation. An example: 1 <?php 2 3 include_once("utils.php"); 4 5 //we can now use the functions in utils.php: 6 $p = getMonthlyPayment(1000, 0.05, 12); 7 8 ?> The include_once function loads and evaluates the given PHP source file at the point in the code in which it is invoked. The “once” in the function refers to the fact that if the source file was already included in the script/code before, it will not be included a second time. This allows you to include the same source file in multiple source files without a conflict. 40.1.3. Calling Functions The syntax for calling a function is to simply provide the function name followed by parentheses containing values or variables to pass to the function. Some examples: 1 $a = 10, $b = 20; 2 $c = sum($a, $b); //c contains the value 30 3 4 //invoke a function with literal values: 5 $dist = getDistance(0.0, 0.0, 10.0, 20.0); 6 7 //invoke a function with a combination: 8 $p = 1500.0; 9 $r = 0.05; 10 $monthlyPayment = getMonthlyPayment($p, $r, 60); 537
ComputerScienceOne_Page_571_Chunk2103
40. Functions 40.1.4. Passing By Reference By default, all types (including numbers, strings, etc.) are passed by value. To be able to pass arguments by reference, we need to use slightly different syntax when defining our functions. To specify that a parameter is to be passed by reference, we place an ampersand, & in front of it in the function signature.1 No other syntax is necessary. When you call the function, PHP automatically takes care of the referencing/dereferencing for you. 1 <?php 2 3 function swap($a, $b) { 4 $t = $a; 5 $a = $b; 6 $b = $t; 7 } 8 9 function swapByRef(&$a, &$b) { 10 $t = $a; 11 $a = $b; 12 $b = $t; 13 } 14 15 $x = 10; 16 $y = 20; 17 18 printf("x = %d, y = %d\n", $x, $y); 19 swap($x, $y); 20 printf("x = %d, y = %d\n", $x, $y); 21 swapByRef($x, $y); 22 printf("x = %d, y = %d\n", $x, $y); 23 24 ?> The first function, swap() passes both variables by value. Swapping the values only affects the copies of the parameters. The original variables $x and $y will be unaffected. In the second function, swapByRef() , both variables are passed by reference as there are ampersands in front of them. Swapping them inside the function swaps the original 1Those familiar with pointers in C will note that this is the exact opposite of the C operator. 538
ComputerScienceOne_Page_572_Chunk2104
40.1. Defining & Using Functions variables. The output to this code is as follows. x = 10, y = 20 x = 10, y = 20 x = 20, y = 10 Observe that when we invoked the function, swapByRef($x, $y); we used the same syntax as the pass by value version. The only syntax needed to pass by reference is in the function signature itself. 40.1.5. Optional & Default Parameters Parameters in PHP functions are optional. You can invoke a function without providing a subset of parameters. However, if a parameter is not provided, PHP will treat the parameter as null . If we invoked the getDistance() function with only two parameters: getDistance(10.0, 20.0); then inside the function, $x1 and $y1 would take on the values 10 and 20, but $x2 and $y2 would be null . When used in the distance formula calculations, both would be treated as zero. If we had invoked the function with no arguments, getDistance(); then all four parameters would be treated as null (and thus zero in the calculations). PHP also allows you to define alternative default values for function parameters. Consider the following example. 1 function getMonthlyPayment($principle, $apr = 0.05, $terms = 60) { 2 $rate = ($apr / 12); 3 $mp = (($principle * $rate) / (1-pow(1+$rate, -$terms))); 4 return round($mp * 100) / 100; 5 } In this example, the second and third parameter have been given default values of 0.05 and 60 respectively. If a call to this function omits these parameters, they are not treated as null , but take on these defaults instead. 1 $x = getMonthlyPayment(10000, 0.07, 72); 2 print $x."\n"; //170.49 3 4 //terms will be 60 5 $x = getMonthlyPayment(10000, 0.07); 539
ComputerScienceOne_Page_573_Chunk2105
40. Functions 6 print $x."\n"; //198.01 7 8 //apr will be 0.05, terms will be 60 9 $x = getMonthlyPayment(10000); 10 print $x."\n"; //188.71 11 12 //balance will be null (0), apr will be 0.05, terms will be 60 13 $x = getMonthlyPayment(); 14 print $x."\n"; //0 but also a warning It would not be possible to invoke getMonthlyPayment() by omitting only the second argument. Providing n arguments will match the first n parameters. Thus, in your function design you should place any optional/default parameters last. 40.1.6. Function Pointers Functions are just pieces of code that reside somewhere in memory just as variables do. Since we can pass variables by reference, it also makes sense that we would do the same with functions. In PHP, functions are first-class citizens2 meaning that you can assign a function to a variable just as you would a numeric value. For example, you can do the following. 1 $func = swapByRef; 2 3 $func($x, $y); In the example above, we assigned the function swapByRef() to the variable $func by using its identifier. The variable essentially holds a reference to the swapByRef() function. Since it refers to a function, we can also invoke the function using the variable as in the last line. This allows you to treat functions as callbacks to other functions. We will revisit this concept in Chapter 47. 40.2. Examples 40.2.1. Generalized Rounding Recall that the standard math library provides a round() function that rounds a number to the nearest whole number. We’ve had need to round to cents as well. We now have 2Some would use a much more restrictive definition of first-class and would not consider them first-class citizens in this sense 540
ComputerScienceOne_Page_574_Chunk2106
40.2. Examples the ability to write a function to do this for us. Before we do, however, let’s think more generally. What if we wanted to round to the nearest tenth? Or what if we wanted to round to the nearest 10s or 100s place? Let’s write a general purpose rounding function that allows us to specify which decimal place to round to. The most natural input would be to specify the place using an integer exponent. That is, if we wanted to round to the nearest tenth, then we would pass it −1 as 0.1 = 10−1, −2 if we wanted to round to the nearest 100th, etc. In the other direction, passing in 0 would correspond to the usual round function, 1 to the nearest 10s spot, and so on. Moreover, we could demonstrate good code reuse (as well as procedural abstraction) by scaling the input value and reusing the functionality already provided in the math library’s round() function. We could further define a roundToCents() function that used our generalized round function. Consider the following. 1 <?php 2 3 /** 4 * Rounds to the nearest digit specified by the place 5 * argument. In particular to the (10^place)-th digit 6 */ 7 function roundToPlace($x, $place) { 8 $scale = pow(10, -$place); 9 $rounded = round(x * $scale) / $scale; 10 return $rounded; 11 } 12 13 /** 14 * Rounds to the nearest cent 15 */ 16 function roundToCents($x) { 17 return roundToPlace($x, -2); 18 } 19 20 ?> We could place these functions into a file named round.php and include them in another PHP source file. 40.2.2. Quadratic Roots Another advantage of passing variables by reference is that we can “return” multiple values with one function call. Functions are limited in that they can only return at most one value. But if we pass multiple parameters by reference, the function can manipulate 541
ComputerScienceOne_Page_575_Chunk2107
40. Functions the contents of them, thereby communicating (though not strictly returning) multiple values. Consider again the problem of computing the roots of a quadratic equation, ax2 + bx + c = 0 using the quadratic formula, x = −b ± √ b2 −4ac 2a Since there are two roots, we may have to write two functions, one for the “plus” root and one for the “minus” root both of which take the coefficients, a, b, c as arguments. However, if we wrote a single function that took the coefficients as parameters by value as well as two other parameters by reference, we could compute both root values, one in each of the by-reference variables. 1 function quadraticRoots($a, $b, $c, &$root1, &$root2) { 2 $discriminant = sqrt($b*$b - 4*$a*$c); 3 $root1 = (-$b + $discriminant) / (2*$a); 4 $root2 = (-$b - $discriminant) / (2*$a); 5 return; 6 } By using pass by reference variables, we avoid multiple functions. Recall that there could be several “bad” inputs to this function. The roots could be complex values, the coefficient a could be zero, etc. In the next chapter, we examine how we can handle these errors. 542
ComputerScienceOne_Page_576_Chunk2108
41. Error Handling & Exceptions Modern versions of PHP support error handling through the use of exceptions. PHP has several different predefined types of exceptions and also allows you to define your own exception types by creating new classes that inherit from the generic Exception class. PHP uses the standard try-catch-finally control structure to handle exceptions and allows you to throw your own exceptions. 41.1. Throwing Exceptions Though PHP defines several different types of exceptions, we’ll only cover the generic Exception class. We can throw an exception in PHP by using the keyword throw and creating a new Exception with an error message. throw new Exception("Something went wrong"); By using a generic Exception , we can only attach a message to the exception (which can be printed by code that catches the exception). If we want more fine-grained control over the type of exceptions, we need to define our own exceptions. 41.2. Catching Exceptions To catch an exception in PHP you can use the standard try-catch control block. Optionally (and as of PHP version 5.5.0) you can use the finally block to clean up any resources or execute code regardless of whether or not an exception was raised. Consider the simple task of reading input from a user and manually parsing its value into an integer. If the user enters a non-numeric value, parsing will fail and we should instead throw an exception. Consider the following function. 1 function readNumber() { 2 $input = readline("Please enter a number: "); 3 if( is_numeric($input) ) { 4 $value = floatval($input); 5 } else { 6 throw new Exception("Invalid input!"); 7 } 8 } 543
ComputerScienceOne_Page_577_Chunk2109
41. Error Handling & Exceptions Elsewhere in the code, we can surround a call to readNumber() in a try-catch statement. 1 try { 2 readNumber(); 3 } catch(Exception $e) { 4 printf("Error: exception encountered: " . $e->getMessage()); 5 exit(1); 6 } In this example, we’ve simply displayed an error message to the standard output and exited the program. We’ve made the design decision that this error should be fatal. We could have chosen to handle this error differently in the catch block. The $e->getMessage() prints the message that the exception was created with. In this case, "Invalid input!" . 41.3. Creating Custom Exceptions As of PHP 5.3.0 it is possible to define custom exceptions by extending the Exception class. To do this, you need to declare a new class. We cover classes and objects in Chapter 45. For now, we present a simple example. Consider the example in the previous chapter of computing the roots of a quadratic polynomial. One possible error situation is when the roots are complex numbers. We could define a new PHP exception class as follows. 1 /** 2 * Defines a ComplexRoot exception class 3 */ 4 class ComplexRootException extends Exception 5 { 6 public function __construct($message = null, 7 $code = 0, 8 Exception $previous = null) { 9 // call the parent constructor 10 parent::__construct($message, $code, $previous); 11 } 12 13 // custom string representation of object 14 public function __toString() { 15 return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; 16 } 17 } 544
ComputerScienceOne_Page_578_Chunk2110
41.3. Creating Custom Exceptions Now in our code we can catch and even throw this new type of exception. 1 if( $b*$b - 4*$a*$c < 0) { 2 throw new ComplexRootException("Cannot Handle complex roots"); 3 } 1 try { 2 $r1 = getRoot($a, $b, $c); 3 } catch(ComplexRootException $e) { 4 //handle here 5 } catch(Exception $e) { 6 //handle all other types of exceptions here 7 } In the code above we had two catch blocks. Since we can have multiple types of exceptions, we can catch each different type and handle them differently if we choose. Each catch block catches a different type of exception. The last catch block was written to catch a generic Exception . Much like an if-else-if statement, the first type of exception that is caught is the block that will be executed and they are all mutually exclusive. Thus, a generic “catch all” block like this should always be the last catch block. The most specific types of exceptions should be caught first and the most general types should be caught last. 545
ComputerScienceOne_Page_579_Chunk2111
42. Arrays PHP allows you to use arrays, but PHP arrays are actually associative arrays. Though you can treat them as regular arrays and use contiguous integer indices, they are more flexible than that. Integer indices need to be contiguous or start at zero and you can use strings as indices. In addition, since PHP is dynamically typed, PHP arrays allow mixed types. An array has no fixed type and you can place different mixed types into the same array. PHP arrays are dynamic, so there is no memory management or allocation/deallocation of memory space. Arrays will grow and shrink automatically as you add and remove elements. 42.1. Creating Arrays Since PHP is dynamically typed, you do not need to declare an array or specify a particular type of variable that it holds. However, there are several ways that you can initialize an array. To create an empty array, you can call the array() function. Optionally, you can provide an initial list of elements to insert into the array by providing the list of elements as arguments to the function. 1 //create an empty array: 2 $arr = array(); 3 4 //create an array with elements 10, 20, 30: 5 $arr = array(10, 20, 30); 6 7 //create an array with mixed types: 8 $arr = array(10, 3.14, "Hello"); 42.2. Indexing By default, when inserting elements, 0-indexing is used. In the three examples above, each element would be located at indices 0, 1, and 2 respectively. The usual square bracket syntax can be used to access and assign elements. 547
ComputerScienceOne_Page_581_Chunk2112
42. Arrays 1 //create an array with elements 10, 20, 30: 2 $arr = array(10, 20, 30); 3 4 //get the first element: 5 $x = $arr[0]; //x has value 10 6 7 //change the 3rd element to 5: 8 $arr[2] = 5; 9 10 //print the 2nd element: 11 printf("$arr[1] = %d\n", $arr[1]); Attempting to access an element at an invalid index does not result in an error or an exception (though a warning may be issued depending on how PHP is setup). Instead, if you attempt to access an invalid element, it will be treated as a null value. 1 $arr = array(10, 20, 30); 2 $x = $arr[10]; //x is null However, an array could have null values in it as elements. How do we distinguish whether or not an accessed value was actually null or if it is not part of the array? PHP provides a function, array_key_exists() to distinguish between these two cases. It returns true or false depending on whether or not a particular index has been set or not. 1 $arr = array(10, null, 30); 2 if(array_key_exists(1, $arr)) { 3 print "index 1 contains an element\n"; 4 } 5 if(!array_key_exists(10, $arr)) { 6 print "index 10 does not contain an element\n"; 7 } 8 9 if($arr[1] === $arr[10]) { 10 print "but they are both null\n"; 11 } 548
ComputerScienceOne_Page_582_Chunk2113
42.2. Indexing 42.2.1. Strings as Indices Since arrays in PHP are associative arrays, keys are not limited to integers. You can also use strings as keys to index elements. 1 $arr = array(); 2 $arr[0] = 5; 3 $arr["foo"] = 10; 4 $arr["hello"] = "world"; 5 6 print "value = " . $arr["hello"]; Note that strings that contain integer values will be type-juggled into their numeric values. For example, $arr["10"] = 3; will be equivalent to $arr[10] = 3; . However, strings containing floating point values will not be coerced but will remain as strings, $arr["3.15"] = 7; for example. 42.2.2. Non-Contiguous Indices Another aspect of PHP associative arrays is that integer indices need not be contiguous. For example, 1 $arr = array(); 2 $arr[0] = 10; 3 $arr[5] = 20; The values at indices 1 through 4 are undefined and the array contains some “holes” in its indices. 42.2.3. Key-Value Initialization Since associative arrays in PHP can be indexed by either integers or strings and need not be ordered or contiguous, we can use a special key-value initialization syntax to define not only the values, but the keys that map to those values when we initialize an array. The “double arrow,” => is used to denote the mapping. 1 $arr = array( 2 "foo" => 5, 3 4 => "bar", 4 0 => 3.14, 549
ComputerScienceOne_Page_583_Chunk2114
42. Arrays 5 "baz" => "ten" 6 ); 42.3. Useful Functions There are dozens of useful functions PHP defines that can be used with arrays. We’ll only highlight a few of the more useful ones. First, the count() function can be used to compute how many elements are stored in the array. 1 $arr = array(10, 20, 30); 2 $n = count($arr); //n is 3 For convenience and debugging, a special function, print_r() allows you to print the contents of an array in a human-readable format that resembles the key-value initialization syntax above. For example, 1 $arr = array( 2 "foo" => 5, 3 4 => "bar", 4 0 => 3.14, 5 "baz" => "ten" 6 ); 7 print_r($arr); would end up printing Array ( [foo] => 5 [4] => bar [0] => 3.14 [baz] => ten ) Two other functions, array_keys() and array_values() return new zero-indexed arrays containing the keys and the values of an array respectively. Reusing the example above, 550
ComputerScienceOne_Page_584_Chunk2115
42.4. Iteration 1 $keys = array_keys($arr); 2 $vals = array_values($arr); 3 print_r($keys); 4 print_r($vals); would print Array ( [0] => foo [1] => 4 [2] => 0 [3] => baz ) Array ( [0] => 5 [1] => bar [2] => 3.14 [3] => ten ) Finally, you can use the equality operators, == and === to compare arrays. The first is the loose equality operator and evaluates to true if the two compared arrays have the same key-value pairs while the second is the strict equality operator and is true only if the arrays have the same key/value pairs in the same order and are of the same type. 42.4. Iteration If we have an array in PHP that we know is 0-indexed and all elements are contiguous, we can use a normal for loop to iterate over its elements by incrementing an index variable. 1 for($i=0; $i<count($arr); $i++) { 2 print $arr[$i] . "\n"; 3 } This fails, however, when we have an associative array that has a mix of integer and string keys or “holes” in the indexing of integer keys. For this reason, it is more reliable to use foreach loops. There are several ways that we can use a foreach loop. The most general usage is to use the double arrow notation to iterate over each key-value pair. 551
ComputerScienceOne_Page_585_Chunk2116
42. Arrays 1 //for each key value pair: 2 foreach($arr as $key => $val) { 3 print "$key maps to $val \n"; 4 } This syntax gives you access to both the key and the value for each element in the array $arr . The keyword as is used to denote the variable names $key and $val that will be changed on each iteration of the loop. You need not use the identifiers $key and $val ; you can use any legal variable names for the key/value variables. If you do not need the keys when iterating, you can use the following shorthand syntax. 1 //for each value: 2 foreach($arr as $val) { 3 print "$val \n"; 4 } 42.5. Adding Elements You can easily add elements to an array by providing an index and using the assignment operator as in the previous examples. There are also several functions PHP defines that can insert elements to the beginning ( array_unshift() ), end ( array_push() ) or at an arbitrary position ( array_splice() ). 1 $arr = array(10, 20, 30); 2 3 array_unshift($arr, 15); 4 //arr is now [15, 10, 20, 30] 5 6 array_push($arr, 25); 7 //arr is now [15, 10, 20, 30, 25] 8 9 //insert 35 at index 3: 10 array_splice($arr, 3, 0, 35); 11 //arr is now [15, 10, 20, 35, 30, 25] Another, simpler way of adding elements is to use the following syntax: 552
ComputerScienceOne_Page_586_Chunk2117
42.6. Removing Elements 1 $arr = array(10, 20, 30); 2 $arr[] = 5; 3 $arr[] = 15; 4 $arr[] = 25; 5 print_r($arr); By using the assignment operator but not specifying the index, the element will be added to the next available integer index. Since there were already 3 elements in the array, each subsequent element is inserted at index 3, 4, and 5 respectively. In general, the element will be inserted at the maximum index value already used plus one. The example above results in the following. Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 5 [4] => 15 [5] => 25 ) 42.6. Removing Elements You can remove elements from an array using the unset() function. This function only removes the element from the array, it does not shift other elements down to fill in the unused index. 1 $arr = array(10, 20, 30); 2 unset($arr[1]); 3 print_r($arr); This example would result in the following. Array ( [0] => 10 [2] => 30 ) Further, you can use unset() to destroy all elements in the array: 553
ComputerScienceOne_Page_587_Chunk2118
42. Arrays unset($arr); destroys the entire array. It does not merely empty the array, but it unsets the variable $arr itself. 42.7. Using Arrays in Functions By default, all arguments to a function in PHP are passed by value; this includes arrays. Thus, if you make any changes to an array passed to a function, the changes are not realized in the calling function. You can explicitly specify that the array parameter is passed by reference so that any changes to the array are realized in the calling function. To illustrate, consider the following example. 1 function setFirst($a) { 2 $a[0] = 5; 3 } 4 5 $arr = array(10, 20, 30); 6 print_r($arr); 7 setFirst($arr); 8 print_r($arr); This example results in the following. Array ( [0] => 10 [1] => 20 [2] => 30 ) Array ( [0] => 10 [1] => 20 [2] => 30 ) That is, the change to the first element does not affect the original array. However, if we specify that the array is passed by reference, then the change is realized. For example, 1 function setFirst(&$a) { 2 $a[0] = 5; 3 } 4 5 $arr = array(10, 20, 30); 554
ComputerScienceOne_Page_588_Chunk2119
42.8. Multidimensional Arrays 6 print_r($arr); 7 setFirst($arr); 8 print_r($arr); This now results in the original array being changed: Array ( [0] => 10 [1] => 20 [2] => 30 ) Array ( [0] => 5 [1] => 20 [2] => 30 ) 42.8. Multidimensional Arrays PHP supports multidimensional arrays in the sense that elements in an array can be of any type, including other arrays. We can use the same syntax and operations for single dimensional arrays. For example, we can use the double arrow syntax and assign arrays as values to create a 2-dimensional array. 1 $mat = array( 2 0 => array(10, 20, 30), 3 1 => array(40, 50, 60), 4 2 => array(70, 80, 90) 5 ); 6 print_r($mat); Which results in the following: Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 ) 555
ComputerScienceOne_Page_589_Chunk2120
42. Arrays [1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) [2] => Array ( [0] => 70 [1] => 80 [2] => 90 ) ) Alternatively, you can use two indices to get and set values from a 2-dimensional array. 1 for($i=0; $i<3; $i++) { 2 for($j=0; $j<4; $j++) { 3 $mat[$i][$j] = ($i+$j)*3; 4 } 5 } which results in: Array ( [0] => Array ( [0] => 0 [1] => 3 [2] => 6 [3] => 9 ) [1] => Array ( [0] => 3 [1] => 6 [2] => 9 [3] => 12 ) [2] => Array ( [0] => 6 [1] => 9 [2] => 12 [3] => 15 ) ) 556
ComputerScienceOne_Page_590_Chunk2121
43. Strings As we’ve previously seen, PHP has a built-in string type. Internally, PHP strings are simply a sequence of bytes, but for our purposes we can treat it as a 0-indexed character array. PHP strings are mutable and can be changed, but it is considered best practice to treat them as immutable and rely on the many functions PHP provides to manipulate strings. 43.1. Basics We can create strings by assigning a string literal value to a variable. Strings can be specified by either single quotes or double quotes (there are no individual characters in PHP, only single character strings), but we will use the double quote syntax. 1 $firstName = "Thomas"; 2 $lastName = "Waits"; 3 4 //we can also reassign values 5 $firstName = "Tom"; The reassignment in the last line in the example effectively destroys the old string. The assignment operator can also be used to make copies of strings. 1 $firstName = "Thomas"; 2 $alias = $firstName; It is important to understand that this assignment makes a deep copy of the string. Changes to the first do not affect the second one. You can make changes to individual characters in a string by treating it like a zero-indexed array. 1 $a = "hello"; 2 $a[0] = "H"; 3 $a[5] = "!"; 4 //a is now "Hello!" 557
ComputerScienceOne_Page_591_Chunk2122
43. Strings The last line extends the string by adding an additional character. You can even remove characters by setting them to the empty string. 1 $a = "Apples!"; 2 $a[5] = ""; 3 //a is now "Apple!" 43.2. String Functions PHP provides dozens of convenient functions that allow you to process and modify strings. We highlight a few of the more common ones here. A full list of supported functions can be found in standard documentation. Because of the history of PHP, many of the same functions defined in the C string library can also be used in PHP. Length When accessing individual characters in a string, it is necessary that we know the length of the string so that we do not access invalid characters (though doing so is not an error, it just results in null ). The strlen() function returns an integer that represents the number of characters in the string. 1 $s = "Hello World!"; 2 $x = strlen($s); //x is 12 3 $s = ""; 4 $x = strlen($s); //x is 0 5 6 //careful: 7 $s = NULL 8 $x = strlen($s); //x is 0 As demonstrated in the last example, strlen() will return 0 for null strings. Recall that we can distinguish between these two situations by using is_null() . Using this function we can iterate over each individual character in a string. 1 $fullName = "Tom Waits"; 2 for($i=0; $i<strlen($fullName); $i++) { 3 printf("fullName[%d] = %s\n", $i, $fullName[$i]); 4 } 558
ComputerScienceOne_Page_592_Chunk2123
43.2. String Functions This would print the following fullName[0] = T fullName[1] = o fullName[2] = m fullName[3] = fullName[4] = W fullName[5] = a fullName[6] = i fullName[7] = t fullName[8] = s Concatenation PHP has a concatenation operator built into the language. To concatenate one or more strings together, you can use a simple period between them as the concatenation operator. Concatenation results in a new string. 1 $firstName = "Tom"; 2 $lastName = "Waits"; 3 4 $formattedName = $lastName . ", " . $firstName; 5 //formattedName now contains "Waits, Tom" Concatenation also works with other variable types. 1 $x = 10; 2 $y = 3.14; 3 4 $s = "Hello, x is " . $x . " and y = " . $y; 5 //s contains "Hello, x is 10 and y = 3.14" Computing a Substring PHP provides a simple function, substr() to compute a substring of a string. It takes at at least 2 arguments: the string to operate on and the starting index. There is a third, optional parameter that allows you to specify the length of the resulting substring. 559
ComputerScienceOne_Page_593_Chunk2124
43. Strings 1 $name = "Thomas Alan Waits"; 2 3 $firstName = substr($name, 0, 6); //"Thomas" 4 $middleName = substr($name, 7, 4); //"Alan" 5 $lastName = substr($name, 12); //"Waits" In the final example, omitting the optional length parameter results in the entire remainder of the string being returned as the substring. 43.3. Arrays of Strings We often need to deal with collections of strings. In PHP we can define arrays of strings. Indeed, we’ve seen arrays of strings before. When processing command line arguments, PHP defines an array of strings, $argv . Each string can be accessed using an index, $argv[0] for example is always the name of the script. We can create our own arrays of strings using the same syntax as with other arrays. 1 $names = array( 2 "Margaret Hamilton", 3 "Ada Lovelace", 4 "Grace Hopper", 5 "Marie Curie", 6 "Hedy Lamarr"); 43.4. Comparisons When comparing strings in PHP, we can use the usual comparison operators such as === , < , or <= which will compare the strings lexicographically. However, this is generally discouraged because of type juggling issues and strict vs loose equality/inequality comparisons. Instead, there are several comparator methods that PHP provides to compare strings based on their content. strcmp($a, $b) takes two strings and returns an integer based on the lexicographic ordering of $a and $b . If $a precedes $b , strcmp() returns something negative. It returns zero if $a and $b have the same content. Otherwise it returns something positive if $b precedes $a . 1 $x = strcmp("apple", "banana"); //x is negative 2 $x = strcmp("zelda", "mario"); //x is positive 560
ComputerScienceOne_Page_594_Chunk2125
43.5. Tokenizing 3 $x = strcmp("Hello", "Hello"); //x is zero 4 5 //shorter strings precede longer strings: 6 $x = strcmp("apple", "apples"); //x is negative 7 8 $x = strcmp("Apple", "apple"); //x is negative In the last example, "Apple" precedes "apple" since uppercase letters are ordered before lowercase letters according to the ASCII table. We can also make case insen- sitive comparisons if we need to using the alternative, strcasecmp($a, $b) . Here, strcasecmp("Apple", "apple") will return zero as the two strings are the same ig- noring the cases. The comparison functions also have length-limited versions, strncmp($a, $b, $n) and strncasecmp($a, $b, $n) . Both will only make comparisons in the first $n characters of the strings. Thus, strncmp("apple", "apples", 5) will result in zero as the two strings are equal in the first 5 characters. 43.5. Tokenizing Recall that tokenizing is the process of splitting up a string along some delimiter. For example, the comma delimited string, "Smith,Joe,12345678,1985-09-08" contains four pieces of data delimited by a comma. Our aim is to split this string up into four separate strings so that we can process each one. PHP provides several functions to to this, explode() and preg_split() . The simpler one, explode() takes two arguments: the first one is a string delimiter and the second is the string to be processed. It then returns an array of strings. 1 $data = "Smith,Joe,12345678,1985-09-08"; 2 3 $tokens = explode(",", $data); 4 //tokens is [ "Smith", "Joe", "12345678", "1985-09-08" ] 5 6 $dateTokens = explode("-", $tokens[3]); 7 //dateTokens is now [ "1985", "09", "08" ] The more sophisticated preg_split() also takes two arguments,1 but instead of a simple delimiter, it uses a regular expression; a sequence of characters that define a search pattern in which special characters can be used to define complex patterns. For 1The “preg” stands for Perl Compatible Regular Expression. 561
ComputerScienceOne_Page_595_Chunk2126
43. Strings example, the complex expression ^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$ will match any valid numerical value including scientific notation. We will not cover regular expressions in depth, but to demonstrate their usefulness, here’s an example by which you can split a string along any and all whitespace: 1 $s = "Alpha Beta \t Gamma \n Delta \t\nEpsilon"; 2 $tokens = preg_split("/[\s]+/", $s); 3 //tokens is now [ "Alpha", "Beta", "Gamma", "Delta", "Epsilon" ] 562
ComputerScienceOne_Page_596_Chunk2127
44. File I/O Because of the history of PHP, file functions, just like string functions, were mostly influenced by the C standard library functions and have very similar naming and usage. Writing binary or plaintext data is determined by which functions you use. In general whether or not a file input/output stream is buffered or unbuffered is determined by the system configuration. There are some ways in which this can be changed, but we will not cover them in detail. 44.1. Opening Files Files are represented in PHP as a “resource” (also referred to as a handle) that can be passed around to other functions to read and write to the file. For our purposes, a resource is simply a variable that can be stored and passed to other functions. To open a file, you use the fopen() function (short for file open) which requires two arguments and returns a file handle. The first argument is the file path/name that you want to open for processing. The second argument is a string representing the “mode” that you want to open the file in. There are several supported modes, but the two we will be interested in are reading, in which case you pass it "r" and writing in which case you pass it "w" . The path can be an absolute path, relative path, or may be omitted if the file is in the current working directory. 1 //open a file for reading (input): 2 $input = fopen("/user/apps/data.txt", "r"); 3 //open a file for writing (output): 4 $output = fopen("./results.txt", "w"); 5 6 if(!$input) { 7 printf("Unable to open input file\n"); 8 exit(1); 9 } 10 11 if(!$output) { 12 printf("Unable to open output file\n"); 13 exit(1); 14 } 563
ComputerScienceOne_Page_597_Chunk2128
44. File I/O 1 $h = fopen("input.data", "r"); 2 while(!feof($h)) { 3 //read the next line: 4 $line = fgets($h); 5 //trim it: 6 $line = trim($line); 7 //process it, we'll just print it 8 print $line; 9 } Code Sample 44.1.: Processing a file line-by-line in PHP The two conditionals above check that the file opened successfully. If opening the file failed, fopen() returns false (and the interpreter issues warning). 44.2. Reading & Writing When a file is opened, the file handle returned by fopen() initially points to the beginning of the file. As you read or write from it, the resource advances through the file content. Reading There are a couple of ways to read input from a file. To read a file line by line, we can use fgets() to get each line. It takes a single argument: the file handle that was returned by fopen() and returns a string containing the entire line including the endline character. If necessary, leading and trailing whitespace can be removed using trim() . To determine the end of a file you can use feof() which returns true when the handle has reached the end of the file. Code Sample 44.1 contains a full example of processing a file line-by-line. Alternatively there is a convenient function, file_get_contents() that will retrieve the entire file as a string. $fileContents = file_get_contents("./inputFile.txt"); Writing There are several ways that we can output to files, but the easiest is to simply use fwrite() (short for file write). This is a “binary-safe” file output function that takes two arguments: the file handle to write to and a string of data to be written. It also returns an integer representing the number of bytes written to the file (or false on 564
ComputerScienceOne_Page_598_Chunk2129
44.2. Reading & Writing error). 1 $x = 10; 2 $y = 3.14; 3 4 //write to a plaintext file 5 fwrite($output, "Hello World!\n"); 6 fwrite($output, "x = $x, y = $y\n"); 44.2.1. Using URLs A nice feature of PHP is that you can use URLs as file names to read and write to a URL. “Reading” from a URL mean connecting to a remote resource, such as a webservice and downloading its contents (which may be HTML, XML or JSON data). Writing to a URL may be used to post data to a web page in order to receive a response. As an example, we can download a webpage in PHP as follows. 1 $h = fopen("http://cse.unl.edu", "r"); 2 $contents = ""; 3 while(!feof($h)) { 4 $contents .= fgets($h); 5 } 6 7 //or just: 8 $contents = file_get_contents("http://cse.unl.edu"); 44.2.2. Closing Files Once you are done processing a file, you should close it using the fclose() function. fclose($h); which takes a single argument, the file handle that you wish to close. 565
ComputerScienceOne_Page_599_Chunk2130
45. Objects Object-oriented features have been continually added to PHP with each new version. Starting with version 5, PHP has had a full, class-based object-oriented programming support, meaning that it facilitates the creation of objects through the use of classes and class declarations. Classes are essentially “blueprints” for creating instances of objects. An object is an entity that is characterized by identity, state and behavior. The identity of an object is an aspect that distinguishes it from other objects. The variables and values that a variable takes on within an object is its state. Typically the variables that belong to an object are referred to as member variables. Finally, an object may also have functions that operate on the data of an object. In the context of object-oriented programming, a function that belongs to an object is referred to as a member method. A class declaration specifies the member variables and member methods that belong to instances of the class. We discuss how to create and use instances of a class below. However, to begin, let’s define a class that models a student by defining member variables to support a first name, last name, a unique identifier, and GPA. To declare a class, we use the class keyword. Inside the class (denoted by curly brackets), we place any code that belongs to the class. To declare member variables in a class, we specify the variable names and their visibility inside the class, but outside any methods in the class. 1 class Student { 2 3 //member variables: 4 private $firstName; 5 private $lastName; 6 private $id; 7 private $gpa; 8 9 } To organize code, it is common practice to place class declarations in separate files with the same name as the class. For example, this Student class declaration would be placed in a file named Student.php and included in any other script files that utilized the class. 567
ComputerScienceOne_Page_601_Chunk2131
45. Objects 45.1. Data Visibility Recall that encapsulation involves not only the grouping of data, but the protection of data. The class declaration above achieves the grouping of data. To provide for the protection of data, PHP defines several visibility keywords that specify what segments of code can “see” the variables. Visibility in this context determines whether or not a segment of code can access and/or modify the variable’s value. PHP defines three levels of visibility using they keywords public , protected and private . Each of these keywords can be applied to both member variables and member methods. • public – This is the least restrictive visibility level and makes the member variable visible to any code segment. • protected – This is a bit more restrictive and makes it so that the member variable is only visible to the code in the same class, or any subclass of the class.1 • private – this is the most restrictive visibility level, private member variables are only visible to instances of the class itself. Table 45.1 summarizes these four keywords with respect to their access levels. It is important to understand that protection is in the context of encapsulation and does not involve protection in the sense of “security.” Protection is this context is a design principle. Limiting the access of variables only affects how the rest of the code base interacts with our class and its data. Modifier Class Subclass World public Y Y Y protected Y Y N private Y N N Table 45.1.: PHP Visibility Keywords & Access Levels In general, it is best practice to make member variables private and control access to them via accessor and mutator methods (see below) unless there is a compelling design reason to increase their visibility. 45.2. Methods The third aspect of encapsulation involves the grouping of methods that act on an object’s data. Within a class, we can declare member methods using the syntax we’re already familiar with. We declare a member method by using the keyword function and providing a signature and body. We can use the same visibility keywords as with member 1Subclasses are involved with inheritance, another object-oriented programming concept that we will not discuss here. 568
ComputerScienceOne_Page_602_Chunk2132
45.2. Methods variables in order allow or restrict access to the methods. With methods, visibility and access determine whether or not the method may be invoked. We add to our example by providing two public methods that compute and return a result on the member variables. We also use javadoc-style comments to document each member method. 1 class Student { 2 3 //member variables: 4 private $firstName; 5 private $lastName; 6 private $id; 7 private $gpa; 8 9 /** 10 * Returns a formatted String of the Student's 11 * name as Last, First. 12 */ 13 public function getFormattedName() { 14 return $this->lastName . ", " . $this->firstName; 15 } 16 17 /** 18 * Scales the GPA, which is assumed to be on a 19 * 4.0 scale to a percentage. 20 */ 21 public function getGpaAsPercentage() { 22 return $this->gpa / 4.0; 23 } 24 25 } There is some new syntax in the example above. In the member methods, we need a way to refer to the instance’s member variables. The keyword $this is used to refer to the instance, this is known as open recursion. When an instance of a class is created, for example, $s = new Student(); the reference variable $s is how we can refer to it. This variable, however, exists outside the class. Inside the class, we need a way to refer to the instance itself. Since we don’t have a variable inside the class to reference the instance itself, PHP provides the keyword $this in order to do so. Then, to access the member variables we use the arrow operator 569
ComputerScienceOne_Page_603_Chunk2133
45. Objects (more below) and reference the member variable via its identifier but with no dollar sign.2 45.2.1. Accessor & Mutator Methods Since we have made all the member variables private , no code outside the class may access or modify their values. It is generally good practice to make member variables private to restrict access. However, if we still want code outside the object to access or mutate (that is, change) the variable values, we can define accessor and mutator methods (or simply getter and setter methods) to facilitate this. Each getter method returns the value of the instance’s variable while each setter method takes a value and sets the instance’s variable to the new value. It is common to name each getter/setter by prefixing a get and set to the variable’s name using lower camel casing. For example: 1 public function getFirstName() { 2 return $this->firstName; 3 } 4 5 public function setFirstName($firstName) { 6 $this->firstName = $firstName; 7 } One advantage to using getters and setters (as opposed to naively making everything public ) is that you can have greater control over the values that your variables can take. For example, we may want to do some data validation by rejecting null values or invalid values. For example: 1 public function setFirstName($firstName) { 2 if($firstName === null) { 3 throw new Exception("names cannot be null"); 4 } else { 5 $this->firstName = $firstName; 6 } 7 } 8 9 public function setGpa($gpa) { 10 if($gpa < 0.0 || $gpa > 4.0) { 2You can use the syntax $this->$foo but it will assume that $foo is a string that contains the name of another variable, for example, if $foo = "firstName"; then $this->$foo would resolve to the instance’s $firstName variable. This is useful if your object has been dynamically created by adding variables at runtime that were not part of the original class declaration. 570
ComputerScienceOne_Page_604_Chunk2134
45.3. Constructors 11 throw new Exception("GPAs must be in [0, 4.0]"); 12 } else { 13 $this->gpa = $gpa; 14 } 15 } Controlling access of member variables through getters and setters is good encapsulation. Doing so makes your code more predictable and more testable. Making your member variables public means that any piece of code can change their values. There is no way to do validation or prevent bad values. In fact, it is good practice to not even have setter methods. If the value of member variables cannot be changed, it makes the object immutable. Immutability is a nice property because it makes instances of the class thread-safe. That is, we can use instances of the class in a multithreaded program without having to worry about threads changing the values of the instance on one another. 45.3. Constructors If we make the (good) design decision to make our class immutable, we still need a way to initialize the values. This is where a constructor comes in. A constructor is a special method that specifies how an object is constructed. With built-in variable types such as an numbers or strings, PHP “knows” how to interpret and assign a value. However, with user-defined objects such as our Student class, we need to specify how the object is created. Just as with functions outside of classes, PHP does not support function overloading inside classes. That is, you can have one and only one function with a given identifier (name). Thus, there is only one possible constructor. Moreover, PHP reserves the name __construct for the constructor method. The two underscores are a naming convention used by PHP to denote “magic methods” that are reserved and have a special purpose in the language. Further, magic methods must be made public . Some magic methods provide default behavior while others do not. For example, if you do not define a constructor method, the default behavior will be to create an object whose member variables all have null values. The following constructor allows a user to construct an instance of our Student instance and specify all four member variables. 1 public function __construct($firstName, $lastName, $id, $gpa) { 2 $this->firstName = $firstName; 3 $this->lastName = $lastName; 4 $this->id = $id; 5 $this->gpa = $gpa; 571
ComputerScienceOne_Page_605_Chunk2135
45. Objects 6 } Though we cannot define multiple constructors, we can use the default value feature of PHP functions to allow a user to call our constructor with a different number of parameters. For example, 1 public function __construct($firstName, $lastName, 2 $id = 0, $gpa = 0.0) { 3 $this->firstName = $firstName; 4 $this->lastName = $lastName; 5 $this->id = $id; 6 $this->gpa = $gpa; 7 } 45.4. Usage Once we have defined our class and its constructors, we can create and use instances of it. With regular variables, we simply need to assign them to an instance of an object and their type will dynamically change to match. To create new instances, we invoke a constructor by using the new keyword and providing arguments to the constructor. 1 $s = new Student("Alan", "Turing", 1234, 3.4); 2 $t = new Student("Margaret", "Hamilton", 4321, 3.9); 3 $u = new Student("John", "Smith"); The process of creating a new instance by invoking a constructor is referred to as instantiation. Once instances have been instantiated, they can be used by invoking their methods via the same arrow operator we used to access member variables. Outside the class, however this will only work if the member method is public . 1 print $t->getFormattedName() . "\n"; 2 3 if($s->getGpa() < $t->getGpa()) { 4 print $t->getFirstName() . " has a better GPA\n"; 5 } 572
ComputerScienceOne_Page_606_Chunk2136
45.5. Common Methods 45.5. Common Methods Another useful magic method is the __toString() method which returns a string representation of the object. Unlike the constructor method, there is no default behavior with the __toString() method. If you do not define this function, it cannot be used (and any attempts to do so will result in a fatal error). We can define the method to return the values of all or some of the class’s variables in whatever format we want. 1 public function __toString() { 2 return sprintf("%s, %s (ID = %d); %.2f", 3 $this->lastName, 4 $this->firstName, 5 $this->id, 6 $this->gpa); 7 } This would return a string containing something similar to "Hamilton, Margaret (ID = 4321); 3.90" 45.6. Composition Another important concept when designing classes is composition. Composition is a mechanism by which an object is made up of other objects. One object is said to “own” an instance of another object. To illustrate the importance of composition, we could extend the design of our Student class to include a date of birth. However, a date of birth is also made up of multiple pieces of data (a year, a month, a date, and maybe even a time and/or locale). We could design our own date/time class to model this, but its generally best to use what the language already provides. PHP 5.2 introduced the DateTime object in which there is a lot of functionality supporting the representation and comparison of dates and time. We can take this concept further and have our own user-defined classes own instances of each other. For example, we could define a Course class and then update our Student class to own a collection of Course objects representing a student’s class schedule (this type of collection ownership is sometimes referred to as aggregation rather than composition). Both of these design updates beg the question: who is responsible for instantiating the instances of $dateOfBirth and the $schedule ? Should we force the “outside” user of our Student class to build a DateTime instance and pass it to a constructor? Should we allow the outside code to simply provide us a date of birth as a string and make the constructor responsible for creating the proper DateTime instance? Do we require that a user create a complete array of Course instances and provide it to the constructor at instantiation? 573
ComputerScienceOne_Page_607_Chunk2137
45. Objects A more flexible approach might be to allow the construction of a Student instance without having to provide a course schedule. Instead, we could add a method that allowed the outside code to add a course to the student. For example, 1 public function addCourse($c) { 2 $this->schedule[] = $c; 3 } This adds some flexibility to our object, but removes the immutability property. Design is always a balance and compromise between competing considerations. 45.7. Example We present the full and completed Student class in Code Sample 45.1. 574
ComputerScienceOne_Page_608_Chunk2138
45.7. Example 1 <?php 2 class Student { 3 4 private $firstName; 5 private $lastName; 6 private $id; 7 private $gpa; 8 private $dateOfBirth; 9 private $schedule; 10 11 public function __construct($firstName, $lastName, $id = 0, $gpa = 0.0, 12 $dateOfBirth = null, $schedule = array()) { 13 $this->firstName = $firstName; 14 $this->lastName = $lastName; 15 $this->id = $id; 16 $this->gpa = $gpa; 17 $this->dateOfBirth = new DateTime($dateOfBirth); 18 $this->schedule = $schedule; 19 } 20 21 public function __toString() { 22 return $this->getFormattedName() . " born " . 23 $this->dateOfBirth->format("Y-m-d"); 24 } 25 26 /** 27 * Returns a formatted String of the Student's 28 * name as Last, First. 29 */ 30 public function getFormattedName() { 31 return $this->lastName . ", " . $this->firstName; 32 } 33 34 /** 35 * Scales the GPA, which is assumed to be on a 36 * 4.0 scale to a percentage. 37 */ 38 public function getGpaAsPercentage() { 39 return $this->gpa / 4.0; 40 } 41 42 public function getFirstName() { 43 return $this->firstName; 44 } 45 46 public function getLastName() { 575
ComputerScienceOne_Page_609_Chunk2139
45. Objects 47 return $this->lastName; 48 } 49 50 public function getId() { 51 return $this->id; 52 } 53 54 public function getGpa() { 55 return $this->gpa; 56 } 57 58 public function addCourse($c) { 59 $this->schedule[] = $c; 60 } 61 62 } 63 64 ?> Code Sample 45.1.: The completed PHP Student class. 576
ComputerScienceOne_Page_610_Chunk2140
46. Recursion PHP supports recursion with no special syntax necessary. However, recursion is generally expensive and iterative or other non-recursive solutions are generally preferred. We present a few examples to demonstrate how to write recursive functions in PHP. The first example of a recursive function we gave was the toy count down example. In PHP it could be implemented as follows. 1 function countDown($n) { 2 if($n===0) { 3 printf("Happy New Year!\n"); 4 } else { 5 printf("%d\n", $n); 6 countDown($n-1); 7 } 8 } As another example that actually does something useful, consider the following recursive summation function that takes an array, its size and an index variable. The recursion works as follows: if the index variable has reached the size of the array, it stops and returns zero (the base case). Otherwise, it makes a recursive call to recSum() , incrementing the index variable by 1. When the function returns, it adds the result to the i-th element in the array. To invoke this function we would call it with an initial value of 0 for the index variable: recSum($arr, 0) . 1 function recSum($arr, $i) { 2 if($i === count($arr)) { 3 return 0; 4 } else { 5 return recSum($arr, $i+1) + $arr[$i]; 6 } 7 } This example was not tail-recursive as the recursive call was not the final operation (the sum was the final operation). To make this function tail recursive, we can carry the summation through to each function call ensuring that the summation is done prior to 577
ComputerScienceOne_Page_611_Chunk2141
46. Recursion the recursive function call. 1 function recSumTail($arr, $i, $sum) { 2 if($i === count($arr)) { 3 return $sum; 4 } else { 5 return recSumTail($arr, $i+1, $sum + $arr[$i]); 6 } 7 } As a final example, consider the following PHP implementation of the naive recursive Fibonacci sequence. An additional condition has been included to check for “invalid” negative values of n for which we throw an exception. 1 function fibonacci($n) { 2 if($n < 0) { 3 throw new Exception("Undefined for n<0."); 4 } else if($n <= 1) { 5 return 1; 6 } else { 7 return fibonacci($n-1) + fibonacci($n-2); 8 } 9 } PHP is not a language that provides implicit memoization. Instead, we need to explicitly keep track of values using a table. In the following example, the table is passed through as an argument. 1 function fibonacciMemoization($n, $table) { 2 if($n < 0) { 3 return 0; 4 } else if($n <= 1) { 5 return 1; 6 } else if(isset($table[$n])) { 7 return $table[$n]; 8 } else { 9 $a = fibonacciMemoization($n-1, $table); 10 $b = fibonacciMemoization($n-2, $table); 11 $result = ($a + $b); 12 $table[$n] = $result; 13 return $result; 578
ComputerScienceOne_Page_612_Chunk2142
14 } 15 } 579
ComputerScienceOne_Page_613_Chunk2143
47. Searching & Sorting PHP provides over a dozen different sorting functions each with different properties and behavior. Recall that PHP has associative arrays which store elements as key-value pairs. Some functions sort by keys, others sort by the value (with some in ascending order, others in descending order). Some functions preserve the key-value mapping and others do not. For simplicity, we will focus on two of the most common sorting functions, sort() , which sorts the elements in ascending order and usort() which sorts according to a comparator function. 47.1. Comparator Functions Consider a “generic” Quick Sort algorithm as was presented in Algorithm 12.6. The algorithm itself specifies how to sort elements, but it doesn’t specify how they are ordered. The difference is subtle but important. Quick Sort needs to know when two elements, a, b are in order, out of order, or equivalent in order to decide which partition each element goes in. However, it doesn’t “know” anything about the elements a and b themselves. They could be numbers, they could be strings, they could be user-defined objects. A sorting algorithm still needs to be able to determine the proper ordering in order to sort. In PHP this is achieved through a comparator function, which is a function that is responsible for comparing two elements and determining their proper order. A comparator function has the following signature and behavior. • The function takes two elements $a and $b to be compared. • The function returns an integer indicating the relative ordering of the two elements: – It returns something negative if $a comes before $b (that is, a < b) – It returns zero if $a and $b are equal (a = b) – It returns something positive if $a comes after $b (that is, a > b) There is no guarantee on the value’s magnitude, it does not necessarily return −1 or +1; it just returns something negative or positive. We’ve previously seen this pattern when comparing strings. The standard PHP library provides a function, strcmp($a, $b) that has the same contract: it takes two strings and returns something negative, zero or something positive depending on the lexicographic ordering of the two strings. The PHP language “knows” how to compare built-in types like numbers and strings. However, to generalize the comparison operation, we can define comparator functions 581
ComputerScienceOne_Page_615_Chunk2144
47. Searching & Sorting that encapsulate more complex logic. As a simple first example, let’s write a comparator function that orders numbers in ascending order. 1 function cmpInt($a, $b) { 2 if($a < $b) { 3 return -1; 4 } else if($a === $b) { 5 return 0; 6 } else { 7 return -1; 8 } 9 } What if we wanted to order integers in the opposite order? We could write another comparator in which the comparisons or values are reversed. Even simpler, we could reuse the comparator above and “flip” the sign by multiplying by −1 (this is one of the purposes of writing functions: code reuse). Even simpler still, we could just flip the arguments we pass to cmpInt() to reverse the order. 1 function cmpIntDesc($a, $b) { 2 return cmpInt($b, $a); 3 } To illustrate some more examples, consider the Student class we defined in Code Sample 45.1. The following code samples demonstrate various ways of ordering Student instances based on one or more of their components. 1 /** 2 * A comparator function to order Student instances by 3 * last name/first name in alphabetic order 4 */ 5 function studentByNameCmp($a, $b) { 6 int result = strcmp($a->getLastName(), $b->getLastName()); 7 if(result == 0) { 8 return strcmp($a->getFirstName(), $b->getFirstName()); 9 } else { 10 return result; 11 } 12 } 582
ComputerScienceOne_Page_616_Chunk2145
47.1. Comparator Functions 1 /** 2 * A comparator function to order Student instances by 3 * last name/first name in reverse alphabetic order 4 */ 5 function studentByNameCmpDesc($a, $b) { 6 return studentByNameCmp($b, $a); 7 } 1 /** 2 * A comparator function to order Student instances by 3 * id in ascending numerical order 4 */ 5 function studentIdCmp($a, $b) { 6 if($a->getId() < $b->getId()) { 7 return -1; 8 } else if($a->getId() === $b->getId()) { 9 return 0; 10 } else { 11 return 1; 12 } 13 } 1 /** 2 * A comparator function to order Student instances by 3 * GPA in descending order 4 */ 5 function studentGpaCmp($a, $b) { 6 if($a->getGpa() > $b->getGpa()) { 7 return -1; 8 } else if($a->getGpa() == $b->getGpa()) { 9 return 0; 10 } else { 11 return 1; 12 } 13 } 583
ComputerScienceOne_Page_617_Chunk2146
47. Searching & Sorting 47.1.1. Searching PHP provides a linear search function, array_search() that can be used to search for an element in an array. The array can be specified to use loose comparisons (default) or strict comparisons. It returns the key (i.e. index) of the first matching element it finds and false if the search was unsuccessful. For example: 1 $arr = array(10, 8, 3, 12, 4, 42, 7, 108); 2 $index = array_search(12, $arr); //index is now 3 3 4 $arr = array("hello", 10, "mixed", 12, "20"); 5 //a loose search: 6 $index = array_search(20, $arr); //index is now 4 7 //a strict search: 8 $index = array_search(20, $arr, false); //index is now false. PHP does not provide a standard binary search function. Though you can write your own binary search implementation, likely the reason that that PHP does not provide one is because one is not needed. The purpose of binary search is to search a sorted array efficiently. However, PHP arrays are not usual arrays: they are associative arrays, essentially key-value maps. Retrieving an element via its key is essentially a constant-time operation, even more efficient that binary search. A better solution may be to simply store the elements using a proper key which can be used to retrieve the element later on. 47.1.2. Sorting PHP’s sort() function can be used to sort elements in ascending order. This is useful if you have arrays of numbers or strings, but doesn’t work very well if you have an array of mixed types or objects. 1 $arr = array("banana", "Apple", "zebra", "apple", "bananas"); 2 sort($arr); 3 //arr is now ("Apple", "apple", "banana", "bananas", "zebra") 4 5 $arr = array(10, 8, 3, 12, 4, 42, 7, 108); 6 sort($arr); 7 //arr is now (3, 4, 7, 8, 10, 12, 42, 108) PHP provides a more versatile sorting function, usort() (user defined sort) that accepts a comparator function that it uses to define the ordering of elements. To pass a comparator function to the usort() function, we pass a string value containing the 584
ComputerScienceOne_Page_618_Chunk2147
47.1. Comparator Functions name of the comparator function we wish to use. Recall that function names in PHP are case insensitive, though it is still best practice to match the naming. Several examples of the usage of this function are presented in Code Sample 47.1. 1 $arr = array(10, 8, 3, 12, 4, 42, 7, 108); 2 usort($arr, "cmpIntDesc"); 3 //arr is now 108, 42, 12, 10, 8, 7, 4, 3 4 5 //roster is an array of Student instances 6 $roster = ... 7 8 //sort by name: 9 usort($roster, "studentByNameCmp"); 10 11 //sort by ID: 12 usort($roster, "studentIdCmp"); 13 14 //sort by GPA: 15 usort($roster, "studentGpaCmp"); Code Sample 47.1.: Using PHP’s usort() Function 585
ComputerScienceOne_Page_619_Chunk2148
Glossary abstraction a technique for managing complexity whereby levels of complexity are established so that higher levels do not see or have to worry about details at lower levels. acceptance testing a phase of software testing that is tested, usually by humans, for acceptability and whether or not it fulfills the business requirements. ad-hoc testing informal software testing method that is done without much planning usually as a “sanity check” to see if a piece of code works and intended for immediate feedback. algorithm a process or method that consists of a specified step-by-step set of operations. 17 anonymous class a class that is defined “inline” without declaring a named class; typi- cally created because the instance has a single use and there is no reason to create multiple instances. 484 anonymous function a function that has no identifier or name, typically created so that it can be passed as an argument to another function as a callback. 144 anti-pattern a common software pattern that is used as a solution to recurring problems that is usually ineffective in solving the problem or introduces risks and other problems; a technical term for common “bad-habits” that can be found in software. 152 array an ordered collection of pieces of data, usually of the same type. assignment operator an operator that allows a user to assign a value to a variable. 33 backward compatible a program, code, library, or standard that is compatible with previous versions so that current and older versions of it can coexist and successfully operate without breaking anything. 29 bar a placeholder name. , see foo baz a placeholder name. , see foo 587
ComputerScienceOne_Page_621_Chunk2149
Glossary bike shedding a phenomenon in projects where a disproportionate amount of time is spent on trivial matters at the expense of spending adequate resources on more important matters. The term was applied to software development by Kamp [24] but derives from Parkinson’s law of triviality [31]. bit the basic unit of information in a digital computer. A bit can be either 1 or 0 (alternatively, true/false, on/off, high voltage/low voltage, etc.). Originally a portmanteau (mash up) of binary digit. 4, 22, 23 Boolean a data type that represents the truth value of a logical statement. Booleans typically have only two values: true or false. 30 bug A flaw or mistake in a computer program that results in incorrect behavior that may have unintended such as errors or failure. The term predates modern computer systems but was popularized by Grace Hopper who, when working with the Mark II computer in 1946 traced a system failure to a moth stuck in a relay. 46, 81, 151 byte a unit of information in a digital computer consisting of 8 bits. 4 cache a component or data structure that stores data in an efficiently retrievable manner so that future requests for the data are fast. 208 call by reference when a variable’s memory address is passed as a parameter to a function, enabling the function to manipulate the contents of the memory address and change the original variable’s value. 142 call by value when a copy of a variable’s value is passed as a parameter to a function; the function has no reference to the original variable and thus changes to the copy inside the function have no effect on the original variable. 140 callback a function or executable unit of code that is passed as an argument to another function with the intention that the function that it is passed to will execute or “call back” the passed function at some point. 144, 366 cargo cult programming refers to the act of including code, patterns, or processes with no real purpose due to a lack of understanding of a bug or of the problem they were attempting to solve or a lack of understanding of the copied code/pattern itself or an inability to adapt it properly.. case sensitive a language is case sensitive if it recognizes differences between lower and upper case characters in identifier names. A language is case insensitive if it does not.. 19 chomp the operation of removing any endline characters from a string (especially when read from a file); may also refer more generally to removing leading and trailing whitespace from a string or “trimming” it. 337, 588
ComputerScienceOne_Page_622_Chunk2150
Glossary closure a function with its own environment in which variables exist. 485 code smell a symptom or common pattern in source code that is usually indicative of a deeper problem or design flaw; smells are usually not bugs and may not cause problems in and of themselves, but instead indicate a pattern of carelessness or low quality of software design or implementation. 152 comparator a function or object that allows you to pass in two elements a, b for com- parison and returns an integer indicating their relative order: something negative, zero, or something positive if a < b, a = b or a > b respectively. 178, 331, 560 compile the process of translating code in a high-level programming language to a low level language such as assembly or machine code. computer engineering a discipline integrating electrical engineering and computer sci- ence that tends to focus on the development of hardware and its interaction with software. computer science the mathematical modeling and scientific study of computation. concatenation the process of combining two (or more) strings to create a new string by appending one of them to the end of the other. 178 constant a variable whose value cannot be changed once set. continuous integration a software development/engineering process by which developer code is merged and shared on a frequent basis. contradiction a logical statement that is always false regardless of the truth values of the statement’s variables. 72 control flow the order in which individual statements in a program are executed or evaluated. 75 Conway’s Law an observation that organizations that build software will inevitably design it as modeling the structure of the organization itself. Attributed to Melvin Conway (1967) who originally stated it as “organizations which design systems . . . are constrained to produce designs which are copies of the communication structures of these organizations”. copy pasta bad coding practice of copy-pasting code and making slight changes when a function or other control structure should be written instead. Copy-pasta practices often lead to poorly designed code, bugs or spaghetti code.. cruft anything that is left over, redundant or getting in the way; in the context of code cruft is code that is no longer needed, legacy or simply poorly written source code. 589
ComputerScienceOne_Page_623_Chunk2151
Glossary dangling pointer when a reference to dynamically allocated memory is lost and the memory can no longer be deallocated, resulting in a memory leak. Alternatively, when a reference points to memory that gets deallocated or reallocated but the pointer remains unmodified, still referencing the deallocated memory. 165 dead code a code segment that has no effect on a program either because it is unused or unreachable (the conditions involving the code will never be satisfied). 72 debug the process of analyzing a program to find a fault or error with the code that leads to bad or unexpected results. 152 debugger a software tool that facilitates debugging; usually a debugger simulates the execution of a program allowing a developer to view the contents of a program as it executes and to “walk” through the execution step by step. 152 deep copy in contrast to a shallow copy, a deep copy is a copy of an array or other piece of data that is distinct from the original. Changes to one copy do not affect the other. 166, 319, 443, 449, 557 defensive programming an approach to programming in which error conditions are checked and handled, preventing undefined or erroneous operations from happening in a program. 38, 48, 84 dynamic programming a technique for solving problems that involves iteratively com- puting values to subproblems, storing them in a table so that they can be used to solve larger versions of the problem. 208 dynamic typing a variable whose type can change during runtime based on the value it is assigned. 31, edge case a situation or input that represents an extreme value or parameter. encapsulation the grouping and protection of data together into one logical entity along with the functionality (functions or methods) that act on that data. 30 enumerated type a data type (usually user defined) that consists of a list of named values. 309, 436 exception an event or occurrence of an erroneous or “exceptional” condition that inter- rupts the normal flow of control in a program, handing control over to exception handler(s). 155 expression a combination of values, constants, literals, variables, operators and possibly function calls such that when evaluated, produce a resulting value. 34 file a resource on a computer stored in memory that holds data. 183 590
ComputerScienceOne_Page_624_Chunk2152
Glossary flowchart a diagram that represents an algorithm or process, showing steps as boxes connected by arrows which establish an order or flow. 17 foo along with “bar,” “baz,” and the full “foobar”, foo is a commonly used placeholder name in programming used to denote generic variables, functions, etc. Usually these terms are used as examples when demonstrating a concept. The terms have a long history [21]. foobar a placeholder name. , see foo function a sequence of program instructions that perform a specific task, packaged as a unit, also known as a subroutine. 133 function overloading the ability to define multiple functions with the same name but with with a different number of or different types of parameters. 145 fuzzing An automated software testing technique that involves providing invalid or random data as input to a program or piece of code to test that it fails in an expected manner.. garbage collection automated memory management in which a garbage collector at- tempts to reclaim memory (garbage) that is no longer being used by a program so that it can be reallocated for other purposes. 165, 383 global scope a variable, function, or other element in a program has global scope if it is visible or has effect throughout the entire program. 32, grok slang, meaning to understand something; originally from Stranger in a Strange Land by Robert A. Heinlein.. hardware (computer hardware) the physical components that make up a computer system such as the processor, motherboard, storage devices, input and output devices, etc.. heisenbug a bug in a program that fails to manifest itself under testing or debugging conditions. Derived from the Heisenberg principle which states that you cannot observe something without affecting it, thus tainting your observations.. hexadecimal base-16 number system using the symbols 0, 1, . . . , 9, A, B, C, D, E, F; usually denoted with a prefix 0x such as 0xff1321ab01 . 470 hoisting usually used in interpreted languages, hoisting involves processing code to find variable or function declarations and processing them before actually executing the code or script. 134 identifier a symbol, token, or label that is used to refer to a variable. Essentially, a variable’s name. 18 591
ComputerScienceOne_Page_625_Chunk2153
Glossary idiom in the context of programming, an idiom is a commonly used pattern, expression or way of structuring code that is well-understood for users of the language. For example, a for-loop structure that iterates over elements in an array. May also refer to a programming design pattern.. 315, immutable an object whose internal state cannot be changed once created, alternatively, one whose internal state cannot be observably changed once created. 390, 423, 449, 466, 571 inheritance an object oriented programming principle that allows you to derive an object from another object, usually to allow for more specificity. input data or information that is provided to a computer program for processing. 41 integration testing a type of software testing used to determine if the integration of different components or modules works or not. interactive a program that is designed to interface with humans by prompting them for input and displaying output directly to them. 41 interactive an informal, abstract, high-level description of a process or algorithm. 41 keyword a word in a programming language with a special meaning in a particular context. In contrast to a reserved word, a keyword may be used for an identifier (variable or function name) but it is strongly discouraged to do so as the keyword already has an intended meaning. kilobyte a unit of information in a digital computer consisting of 1024 bytes (equivalently, 210 bytes), KB for short. kludge a poorly designed or “thrown-together” solution; a design that is a collection of ill-fitting parts that may be functional, but is fragile and not easily maintained. lambda expression another term for anonymous functions. 144, 493 lexicographic a generalization of the usual dictionary order as codified with the ASCII character table. 178 linking the process of generating an executable file from (multiple) object files. lint (or linter) a static code analysis tool that analyzes code for suspicious or error-prone code that is likely to cause problems. 152 literal in a programming language, a literal is notation for specifying a value such as a number of string that can be directly assigned to a variable. 29, 34 load testing a form of performance testing used to determine to what extent a piece of software or a system can handle a high demand or “load”. 592
ComputerScienceOne_Page_626_Chunk2154
Glossary magic number a value used in a program with unexplained, undocumented, or am- biguous meaning, usually making the code less understandable. 258, 309, 310, 437 mantissa the part of a floating-point number consisting of its significant digits (called a significand in scientific notation). 25 map a data structure that allows you to store elements as key-value pairs with the key mapping to a value. memoization a technique which uses a table to store previously computed values of a function so that they do not need to be recomputed, essentially the table serves as a cache. 208 memory leak the gradual loss of memory when a program fails to deallocate or free up unused memory, degrading performance and possibly resulting in the termination of the program when memory runs out. 165, 320, 326 naming convention a set of guidelines for choosing identifier names for variables, func- tions, etc. in a programming language. Conventions may be generally accepted by all developers of a particular language or they may be established for use in a particular library, framework, or organization. 20 network a collection of two or more computer systems linked together through a physical connection over which data can be transmitted using some protocol. octal base-8 number system using the symbols 0, 1, 2, . . . , 6, 7; usually denoted with a single leading zero such as 0123742 . open recursion a mechanism by which an object is able to refer to itself usually using a keyword such as this or self .. 200, 465, 569 operand the arguments that an operator applies to. 33 operator a symbol used to denote some transformation that combines or changes the operands it is applied to to produce a new value. 33 order of precedence the order in which operators are evaluated, multiplication is per- formed before addition for example. 38 output data or information that is produced as the result of the execution of a program. 41 overflow when an arithmetic operation results in a number that is larger than the specified type can represent overflow occurs resulting in an invalid result. 39 parse to process data to identify its individual components or elements. 179, 593
ComputerScienceOne_Page_627_Chunk2155
Glossary persistence the characteristic of data that outlives the process or program that created it; the saving of data across multiple runs of a program. 183 pointer a reference to a particular memory location in a computer. 30, 295 polymorphism an object oriented programming concept that allows you to treat a variable, method, or object as different types. primitive a basic data type that is defined and provided by a programming language. Typically numeric and character types are primitive types in a language for example. Generally, the user doesn’t need to define the operations involving primitive types as they are defined by the language. Primitive data types are used as the basic building blocks in a program and used to compose more complex user-defined types. 30, 390 procedural abstraction the concept that a procedure or sequence of operations can be encapsulated into one logical unit (function, subroutine, etc.) so that a user need not concern themselves with the low-level details of how it operates. 134 program stack also referred to as a call stack, it is an area of memory where stack frames are stored for each function call containing memory for arguments, local variables and return values/addresses. 137 protocol a set of rules or procedures that define how communication takes place. pseudocode the act of a program asking a user to enter input and subsequently waiting for the user to enter data. 13 query an operation that retrieves data, typically from a database. 152 queue a data structure that store elements in a FIFO (First-In First-Out) manner; elements can be added to the end of a queue by an enqueue operation and removed from the start of a queue by a dequeue operation. radix the base of a number system. Binary, octal, decimal, hexadecimal would be base 2, 8, 10, and 16 respectively. reentrant a function that can be interrupted during its execution while another thread can successfully invoke the function without the two functions interfering with the data used in either function call. 334 refactor the process of modifying, updating or restructuring code without changing its external behavior; refactoring may be done to make code more efficient, more readable, more reliable, or simply to bring it into compliance with style or coding conventions. reference a reference in a computer program is a variable that refers to an object or function in memory. 30 594
ComputerScienceOne_Page_628_Chunk2156
Glossary regression testing a type of software testing that tests software that previously passed testing but that was changed or refactored in some way. Regression testing tests to see if the software still passes the tests or not in which case it is said to have “regressed”. regular expression a sequence of characters in which special characters and directives can be used to define a complex pattern that can be searched and matched in another string or data. 455, 561 reserved word a word or identifier in a language that has a special meaning to the syntax of the language and therefore cannot be used as an identifier in variables, functions, etc.. 19 scope the scope of a variable, method, or other entity in a program is the part of the program in which the name or reference of the entity is bound. That is, the part of the program that “knows” about the variable in which the variable can be accessed, changed, or used. 32, 255, 386 segmentation fault a fault or error that arises when a program attempts to access a segment of memory that it is not allowed access to, usually resulting in the program being terminated by the operating system. 296, 315 shallow copy in contrast to a deep copy, a shallow copy is merely a reference that refers to the original array or piece of data. The two references point to the same data, so if the data is modified, both references will realize it.. 166, 319, 443 short circuiting the process by which the second operand in a logical statement is not evaluated if the value of the expression is determined by the first operand. 74 signature a function signature is how a function is uniquely identified. A signature includes the name (identifier) of the function, its parameter list (and maybe types) and the return type. 134 software any set of machine-readable instructions that can be executed in a computer processor. software engineering the study and application of engineering principles to the design, development, and maintenance of complex software systems. spaghetti code a negative term used for code that is overly complex, disorganized or unstructured code. stack a data structure that stores elements in a LIFO (last-in first-out) manner; elements can be added to a stack via a push operation which places the element on the “top” of the stack; elements can be removed from the top of the stack via a pop operation. 137, 206 595
ComputerScienceOne_Page_629_Chunk2157
Glossary stack overflow when a program runs out of stack space, it may result in a stack overflow and the termination of the program. 205 static analysis the analysis of software that is performed on source (or object) code without actually running or compiling a program usually by using an automated tool that can detect actual or potential problems with the source code (other than syntactic problems that could easily be found by a compiler). 152 static dispatch when function overloading is supported in a language, this is the mecha- nism by which the compiler determines which function should be called based on the number and type of arguments passed to the function when it is called. 145 static typing a variable whose type is specified when it is created (declared) and does not change while the variable remains in scope. 31, string a data type that consists of a sequence of characters which are encoded under some encoding standard such as ASCII or Unicode. 27, 177 string concatenation an operation by which a string and another data type are combined to form a new string. 37 syntactic sugar syntax in a language or program that is not absolutely necessary (that is, the same thing can be achieved using other syntax), but may be shorter, more convenient, or easier to read/write. In general, such syntax makes the language “sweeter” for the humans reading and writing it. 40, 82, 102, 161, 451 tautology a logical statement that is always true regardless of the truth values of the statement’s variables. 72 test case an input/output pair that is known to be correct that is to be used to test a unit of software. test case a collection of tests that are used to test a piece or collection of software. token when something (usually a string) is parsed, the individual components or elements are referred to as tokens. 179 top-down design an approach to problem solving where a problem is broken down into smaller parts. 3, 133 transpile to (automatically) translate code in one programming language into code in another programming language, usually between two high-level programming languages. truncation removing the fractional part of a floating-point number to make it an integer. Truncation is not a rounding operation. 36, 263, 394, 596
ComputerScienceOne_Page_630_Chunk2158
Glossary two’s complement A way of representing signed (positive and negative) integers using the first bit as a sign bit (0 for positive, 1 for negative) and where negative numbers are represented as the complement with respect to 2n (the result of subtracting the number from 2n) . 24 type a variable’s type is the classification of the data it represents which could be numeric, string, boolean, or a user defined type. 22 type casting converting or variable’s type into another type, for example, converting an integer into a more general floating-point number, or converting a floating-point number into an integer, truncating and losing the fractional part. 36, 263, 394 underflow when an arithmetic operation involving floating-point numbers results in a number that is smaller than the smallest representable number underflow occurs resulting in an invalid result. 39 Unicode an international character encoding standard used in programming languages and data formats. 449 unit test software testing method that tests an individual “unit” of code; depending on the context, a unit may refer to an individual function, class, or module. unwinding the process of removing a stack frame when returning from a function. 164 validation the process of verifying that data is correct or conforms to certain expectations including formatting, type, range of values, represents a valid value, etc.. 42 variable a memory location which stores a value that may be set using an assignment operator. Typically a variable is referred to using a name or identifier. 18 widget a generic term for a graphical user interface component such as a button or text box. yak shaving an ostensibly pointless activity that despite its uselessness allows you to overcome a a difficulty and solve a larger problem. Basically, screwing around until you become familiar enough with the problem that the solution presents itself. Attributed to Carlin Vieri who took it from an episode of Ren and Stimpy.. 597
ComputerScienceOne_Page_631_Chunk2159
Acronyms ACID Atomicity Consistency Isolation Durability. ACM Association for Computing Machinery. ALU Arithmetic and Logic Unit. 4 ANSI American National Standards Institute. 253 API Application Programmer Interface. 15, 184, 436 ASCII American Standard Code for Information Interchange. 27, 66, 183, 187, 260, 325, 332, 385, 391, 454, 561 BYOD Bring Your Own Device. CE Computer Engineering. CI Continuous Integration. CJK Chinese Japanese Korean. 29 CLA Command Line Arguments. CLI Command Line Interface. 46 CMS Content Management System. 497 CMYK Cyan-Magenta-Yellow-Key. CPU Central Processing Unit. 4, 74 CRUD Create Retrieve Update Destroy. CS Computer Science. CSS Cascading Style Sheets. CSV Comma Separated Values. 179, 337 CWD Current Working Directory. 184 CYA Cover Your Ass. 599
ComputerScienceOne_Page_633_Chunk2160
Acronyms DRY Don’t Repeat Yourself. 292 EB Exabyte. ECMA European Computer Manufacturers Association. EDI Electronic Data Interchange. EOF End Of File. 184 FIFO First-In First-Out. FOSS Free and Open Source Software. FUD Fear Uncertainty Doubt. GB Gigabyte. GCC GNU Compiler Collection. GDB GNU Debugger. GIF Graphics Interchange Format. GIGO Garbage-In Garbage-Out. GIMP GNU Image Manipulation Program. GIS Geographic Information System. GNU GNU’s Not Unix!. 49, 324 GUI Graphical User Interface. 42, 144, 366 HTML HyperText Markup Language. 181, 184, 497, 565 IDE Integrated Development Environment. 7, 21, 46, 49, 258, 385, 390, 471, 502 IEC International Electrotechnical Commission. 26, 253 IEEE Institute of Electrical and Electronics Engineers. 26, 260, 306, 503 IP Internet Protocol. 201 ISO International Organization for Standardization. 253, 343 JDBC Java Database Connectivity. JDK Java Development Kit. 383, 385, 388, 427, 431, 436, 449, 458, 487 600
ComputerScienceOne_Page_634_Chunk2161
Acronyms JEE Java Enterprise Edition. JIT Just In Time. 12 JPEG Joint Photographic Experts Group. 183 JRE Java Runtime Environment. JSON JavaScript Object Notation. 185, 565 JVM Java Virtual Machine. 12, 383, 384, 389, 423, 431, 435, 440, 442, 449, 467, 470, 484 KB Kilobyte. 162, 460 KISS Keep It Simple, Stupid. LIFO Last-In First-Out. 137 LOC Lines Of Code. MAC Media Access Control. 201 MB Megabyte. 162 MP3 MPEG-2 Audio Layer III. MPEG Moving Picture Experts Group. MVP Minimum Viable Product. MWE Minimum Working Example. 254 NIST National Institute of Standards and Technology. ODBC Open Database Connectivity. OEM Original Equipment Manufacturer. OOP Object-Oriented Programming. 177, 384, 386, 433, 444, 499 PB Petabyte. PDF Portable Document Format. 15 PHP PHP: Hypertext Preprocessor (a recursive backronym; used to stand for Personal Home Page). PNG Portable Network Graphics. 601
ComputerScienceOne_Page_635_Chunk2162
Acronyms POJO Plain Old Java Object. POSIX Portable Operating System Interface. 259, 306, 336, 343 RAM Random Access Memory. 5 REPL Read-Eval-Print Loop. RGB Red-Green-Blue. ROM Read-Only Memory. RTFM Read The “Freaking” Manual. RTM Read The Manual. SD Software Development. SDK Software Development Kit. 443, 444 SE Software Engineering. SEO Search Engine Optimization. SQL Structured Query Language. 431, 436 SSL Secure Sockets Layer. 296 STEAM Science, Technology, Engineering, Art, and Math. STEM Science, Technology, Engineering, and Math. TB Terabyte. TCP Transmission Control Protocol. TDD Test-Driven Development. TSV Tab Separated Values. 179 TUI Text User Interface. UI User Interface. UML Unified Modeling Language. URL Uniform Resource Locator. UTC Coordinated Universal Time. 343 UTF-8 Universal (Character Set) Transformation Format–8-bit. 602
ComputerScienceOne_Page_636_Chunk2163
Acronyms UX User Experience. VLSI Very Large Scale Integration. 4 W3C World Wide Web Consortium. WWW World Wide Web. 181, 383, 497 XML Extensible Markup Language. 21, 185, 565 YAGNI You Ain’t Gonna Need It. 603
ComputerScienceOne_Page_637_Chunk2164
Index aggregation, 199 algorithm, 215 anonymous class, 484 arrays, 159 in C, 313 in Java, 439 in PHP, 547 indexing, 160 iteration, 161 multidimensional, 166 static, see static array160 arrow operator, 347 assignment operator, 33 associative arrays, 168 bandwidth, 5 basic input, 41 basic output, 41 binary, 4, 23 counting, 23 binary search, 213 analysis, 218 C, 373 bit, 4 block, see code block Boolean, 30 bottom-up design, 3, 200 buffered, 187 bug, 151 byte, 4 C arrays, 313 comparators, 361 conditionals, 271 error handling, 305 file I/O, 335 functions, 291 loops, 283 recursion, 357 strings, 325 cache, 208 call by reference, 140 call by value, 140 call stack, 7 callback, 144, 366 calling functions, see invoking functions case sensitive, 19 class, 198, 386 class-based, 198 code block, 13 command line arguments, 44 comment, 14 comparator, 178, 238, 239, 361 in Java, 483 comparison operators, 66 compiled language, 7 composition, 199, 344, 472 compound logic, 71 computer, 4 conditionals, 65 if statement, 75 if-else statement, 76 if-else-if statement, 78 in C, 271 in Java, 403 in PHP, 515 conjunction, see logical operators–and constants, 33 605
ComputerScienceOne_Page_639_Chunk2165
Index constructor, 199, 467 contradiction, 72 control flow, 17 copy constructor, 468 De Morgan’s laws, 72 debugger, 152 debugging, 46, 49 deep copy, 166, 353 defensive programming, 48, 84, 153 disjunction, see logical operators–or do-while loop, 100 dot operator, 346 dynamic memory, 164 dynamic programming, 208 dynamic typing, 31 elementary operation, 215 encapsulation, 30, 197 C, 341 enumerated type, 30 enumerated types in Java, 436 error code, 154 error handling, 151 exception, 155 in C, 305 in Java, 431 in PHP, 543 exception, 155 fatal error, 153 file, 183 file I/O, 183 in C, 335 in Java, 457 in PHP, 563 first-class citizen, 142 floating point number, 25 flowchart, 17 for loop, 99 foreach loop, 102, 161 function hoisting, 535 function pointers, 365 function prototype, 291 functional programming, 142 functions, 133 in C, 291 in Java, 423 in PHP, 535 garbage collection, 165 Gauss’s Formula, 222 generic programming, 212 global scope, 32 graphical user interface, 42 hardware, 4 heap, 160 Heap Sort, 237 Hello World C, 253 hello world Java, 384 hexadecimal, 5 hoisting, 134, 535 identifier, 18 if statement, 75 if-else statement, 76 if-else-if statement, 78 immutable, 423 index, 160 infinite loop, 97, 103 Insertion Sort, 224 Integrated Development Environment, 7 interpreted language, 7 invoking functions, 136 Java arrays, 439 Comparators, 483 conditionals, 403 enumerated types, 436 error handling, 431 file I/O, 457 loops, 415 methods, 423 objects, 461 recursion, 479 606
ComputerScienceOne_Page_640_Chunk2166
Index strings, 449 kilobyte, 4 lambda expression, 493 linear search, 212 C, 372 linked list, 167 linter, 152 list in Java, 444 lists, 167 literal, 34 logic errors, 48 logical operators, 65 and, 69 negation, 68 or, 70 loops, 95 do-while loop, 100 for loop, 99 foreach loop, 102 in C, 283 in Java, 415 in PHP, 527 infinite loop, 103 while loop, 97 lower camel casing, 20 main memory, 5 mantissa, 25 maps, 168 member methods, 198 member variables, 198 memoization, 208, 358 memory, 5 memory leak, 165, 326 memory management, 165 Merge Sort, 232 method overloading, 423 multidimensional arrays, 166, 443 natural order, 242 nested loops, 103 nesting, 84 null, 30 object, 30, 197 objects, 197 defining, 198 in Java, 461 using, 200 open recursion, 200, 465 in PHP, 569 operator, 33 logical, 65 operators addition, 35 arithmetic, 35 assignment, see asignment opera- tor33 C, 262 compound assignment, 40 division, 35 increment, 40 integer division, 37 multiplication, 35 negation, 35 string concatenation, 37 subtraction, 35 optional parameters, 145 order of precedence, 38 logic, 73 overflow, 39 overloading, 483 parse, 179 pass by reference, 297, 423 pass by value, 423 paths, 184 absolute, 184 relative, 184 persistence, 183 PHP arrays, 547 conditionals, 515 error handling, 543 file I/O, 563 functions, 535 607
ComputerScienceOne_Page_641_Chunk2167
Index loops, 527 magic method, 571 recursion, 577 strings, 557 pointers, 295 pollute the namespace, 33 polymorphism, 374 preprocessor directive, 255 primitive types, 30 printf, 43 problem solving, 2 procedural abstraction, 134, 301 program stack, 137 pseudocode, 13, 50 Quick Sort, 227 recursion, 203 C, 357 in Java, 479 in PHP, 577 reentrant, 334 regression testing, 48 runtime errors, 47 scope, 32, 134 global, 137 local, 136 search binary search, 213 linear search, 212 search algorithm analysis, 215 searching, 211 segmentation fault, 264, 296 Selection Sort, 221 analysis, 222 sequential control flow, 13 set, 167 in Java, 446 sets, 167 shallow copy, 166, 353 short circuiting, 74 software, 4 software testing, 48 Sorting C, 374 sorting, 211, 220 Heap Sort, 237 Insertion Sort, 224 Merge Sort, 232 Quick Sort, 227 Selection Sort, 221 stability, 243 Tim Sort, 237 stack overflow, 162, 345 standard input, 42 standard output, 42 static array, 160 static typing, 31 static vs dynamic memory, 162 strings, 27, 177 comparison, 178 in C, 325 in Java, 449 in PHP, 557 tokenizing, 179 structures, 341 arrays, 348 defining, 341 style guide, 20, 22 syntactic sugar, 40 syntax error, 13, 47 tail recursion, 205 tautology, 72 ternary if-else operator, 82 test case, 49 test cases, 48 testing, 3 Tim Sort, 237 top-down design, 3, 133 transpiler, 12 truncation, 36 try-with-resources, 458 two’s complement, 24 type casting, 36, 263 type juggling, 505 unbuffered, 187 608
ComputerScienceOne_Page_642_Chunk2168
Index underflow, 39 underscore casing, 20 unicode, 29 upper camel casing, 20 use case, 3 vararg function, 145, 424 variable, 18 identifier, 18 naming conventions, 19 naming rules, 19 scope, 32 types, 22 variable argument function, see vararg function variables C, 260 visibility, 197, 424, 462 while loop, 97 609
ComputerScienceOne_Page_643_Chunk2169
Bibliography [1] Mars climate orbiter. http://mars.jpl.nasa.gov/msp98/orbiter/, 1999. [Online; accessed 17-March-2015]. [2] Moth in the machine: Debugging the origins of ‘bug’. Computer World Magazine, September 2011. [3] errno.h: system error numbers - base definitions reference. http://pubs.opengroup. org/onlinepubs/9699919799/basedefs/errno.h.html, 2013. [Online; accessed 13-September-2015]. [4] ISO/IEC 9899 - Programming Languages - C. http://www.open-std.org/JTC1/ SC22/WG14/www/standards, 2013. [5] Java platform standard edition 7. http://docs.oracle.com/javase/7/docs/api/, 2015. [Online; accessed 10-February-2015]. [6] List of software bugs. https://en.wikipedia.org/wiki/List_of_software_bugs, 2015. [Online; accessed 12-September-2015]. [7] Unchecked exceptions — the controversy. https://docs.oracle.com/javase/ tutorial/essential/exceptions/runtime.html, 2015. [Online; accessed 15- September-2015]. [8] Douglas Adams. Dirk Gently’s Holistic Detective Agency. Pocket Books, 1987. [9] Jon L. Bentley and M. Douglas McIlroy. Engineering a sort function. Softw. Pract. Exper., 23(11):1249–1265, November 1993. [10] Joshua Bloch. Extra, extra - read all about it: Nearly all binary searches and mergesorts are broken. http://googleresearch.blogspot.com/2006/06/ extra-extra-read-all-about-it-nearly.html, 2006. [11] Michael Braukus. NASA honors apollo engineer. NASA News, September 2003. [12] IEEE Computer Society. Portable Applications Standards Committee, England) Open Group (Reading, Institute of Electrical, Electronics Engineers, and IEEE- SA Standards Board. Standard for Information Technology: Portable Operating System Interface (POSIX) : Base Specifications. Number Issue 7 in IEEE Std. 2008. 611
ComputerScienceOne_Page_645_Chunk2170
Bibliography [13] Edsger W. Dijkstra. Why numbering should start at zero. https://www.cs.utexas. edu/users/EWD/transcriptions/EWD08xx/EWD831.html, 1982. [Online; accessed September 25, 2015]. [14] Bruce Eckel. Thinking in Java. Prentice Hall PTR, Upper Saddle River, NJ, USA, 4th edition, 2005. [15] Internet Goons. Do i cast the result of malloc? http://stackoverflow. com/questions/605845/do-i-cast-the-result-of-malloc. [Online; accessed September 27, 2015]. [16] Arend Heyting. Die formalen Regeln der intuitionistischen Logik. Berlin, 1930. First use of the notation ¬ as a negation operator. [17] C. A. R. Hoare. Algorithm 64: Quicksort. Commun. ACM, 4(7):321–, July 1961. [18] C. A. R. Hoare. Quicksort. The Computer Journal, 5(1):10–16, 1962. [19] IEC. IEC 60559 (1989-01): Binary floating-point arithmetic for microprocessor systems. 1989. This Standard was formerly known as IEEE 754. [20] IEEE Task P754. IEEE 754-2008, Standard for Floating-Point Arithmetic. August 2008. [21] Donald E. Eastlake III, Carl-Uno Manros, and Eric S. Raymond. Etymology of ”foo”. RFC, 3092:1–14, 2001. [22] ISO. ISO 8601:1988. Data elements and interchange formats — Information inter- change — Representation of dates and times. 1988. See also 1-page correction, ISO 8601:1988/Cor 1:1991. [23] John McCarthy. Towards a mathematical science of computation. In In IFIP Congress, pages 21–28. North-Holland, 1962. [24] Poul-Henning Kamp. The bikeshed email. http://phk.freebsd.dk/sagas/ bikeshed.html. [Online; accessed September 12, 2016]. [25] Brian W. Kernighan. Programming in C – A Tutorial. Bell Laboratories, Murray Hill, New Jersey, 1974. [26] Brian W. Kernighan. The C Programming Language. Prentice Hall Professional Technical Reference, 2nd edition, 1988. [27] Donald E. Knuth. Von neumann’s first computer program. ACM Comput. Surv., 2(4):247–260, December 1970. [28] Tony Long. The man who saved the world by doing ... nothing. Wired, September 2007. 612
ComputerScienceOne_Page_646_Chunk2171
Bibliography [29] M. V. Wilkes, D. J. Wheeler and S. Gill. The preparation of programs for an electronic digital computer, with special reference to the EDSAC and the use of a library of subroutines. Addison-Wesley Press, Cambridge, Mass., 1951. [30] United States Government Accountability Office. COLLEGE TEXTBOOKS: Stu- dents have greater access to textbook information (gao-13-368), 2013. [31] Cyril Northcote Parkinson. Parkinson’s Law, or the Pursuit of Progress. John Murray, London, 1958. [32] Richard E. Pattis. Textbook errors in binary searching. In Proceedings of the Nineteenth SIGCSE Technical Symposium on Computer Science Education, SIGCSE ’88, pages 190–194, New York, NY, USA, 1988. ACM. [33] Giuseppe Peano. Studii de Logica Matematica. In Atti della Reale Accademia delle scienze di Torino, volume 32 of Classe di Scienze Fisiche Matematiche e Naturali, pages 565–583. Accademia delle Scienze di Torino, Torino, April 1897. [34] Tim Peters. [Python-Dev] Sorting. Python-Dev mailing list, https://mail.python. org/pipermail/python-dev/2002-July/026837.html, July 2002. [35] Bertrand Russell. The theory of implication. American Journal of Mathematics, 28:159–202, 1906. [36] Bruce A. Tate. Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages. Pragmatic Bookshelf, 1st edition, 2010. [37] Alfred North Whitehead and Bertrand Arthur William Russell. Principia mathe- matica; vol. 1. Cambridge Univ. Press, Cambridge, 1910. [38] J. W. J. Williams. Algorithm 232: Heapsort. Communications of the ACM, 7(6):347– 348, 1964. 613
ComputerScienceOne_Page_647_Chunk2172
ELECTROMAGNETICS STEVEN W. ELLINGSON VOLUME 2
Electromagnetics_Vol2_Page_1_Chunk2173
ELECTROMAGNETICS VOLUME 2
Electromagnetics_Vol2_Page_2_Chunk2174
Publication of this book was made possible in part by the Virginia Tech University Libraries’ Open Education Initiative Faculty Grant program: http://guides.lib.vt.edu/oer/grants Books in this series Electromagnetics, Volume 1, https://doi.org/10.21061/electromagnetics-vol-1 Electromagnetics, Volume 2, https://doi.org/10.21061/electromagnetics-vol-2 Te Open Electromagnetics Project, https://www.faculty.ece.vt.edu/swe/oem
Electromagnetics_Vol2_Page_3_Chunk2175
ELECTROMAGNETICS STEVEN W. ELLINGSON VOLUME 2
Electromagnetics_Vol2_Page_4_Chunk2176
Copyright © 2020 Steven W. Ellingson iv This work is published by Virginia Tech Publishing, a division of the University Libraries at Virginia Tech, 560 Drillfield Drive, Blacksburg, VA 24061, USA (publishing@vt.edu). Suggested citation: Ellingson, Steven W. (2020) Electromagnetics, Vol. 2. Blacksburg, VA: Virginia Tech Publishing. https://doi.org/10.21061/electromagnetics-vol-2. Licensed with CC BY-SA 4.0. https://creativecommons.org/licenses/by- sa/4.0. Peer Review: This book has undergone single-blind peer review by a minimum of three external subject matter experts. Accessibility Statement: Virginia Tech Publishing is committed to making its publications accessible in accordance with the Americans with Disabilities Act of 1990. The screen reader–friendly PDF version of this book is tagged structurally and includes alternative text which allows for machine-readability. The LaTeX source files also include alternative text for all images and figures. Publication Cataloging Information Ellingson, Steven W., author Electromagnetics (Volume 2) / Steven W. Ellingson Pages cm ISBN 978-1-949373-91-2 (print) ISBN 978-1-949373-92-9 (ebook) DOI: https://doi.org/10.21061/electromagnetics-vol-2 1. Electromagnetism. 2. Electromagnetic theory. I. Title QC760.E445 2020 621.3 The print version of this book is printed in the United States of America. Cover Design: Robert Browder Cover Image: © Michelle Yost. Total Internal Reflection (https://flic.kr/p/dWAhx5) is licensed with a Creative Commons Attribution-ShareAlike 2.0 license: https://creativecommons.org/licenses/by-sa/2.0/ (cropped by Robert Browder) This textbook is licensed with a Creative Commons Attribution Share-Alike 4.0 license: https://creativecommons.org/licenses/by-sa/4.0. You are free to copy, share, adapt, remix, transform, and build upon the material for any purpose, even commercially, as long as you follow the terms of the license: https://creativecommons.org/licenses/by-sa/4.0/legalcode.
Electromagnetics_Vol2_Page_5_Chunk2177
v Features of This Open Textbook Additional Resources The following resources are freely available at http://hdl.handle.net/10919/93253 Downloadable PDF of the book LaTeX source files Slides of figures used in the book Problem sets and solution manual Review / Adopt /Adapt / Build upon If you are an instructor reviewing, adopting, or adapting this textbook, please help us understand your use by completing this form: http://bit-ly/vtpublishing-update. You are free to copy, share, adapt, remix, transform, and build upon the material for any purpose, even commercially, as long as you follow the terms of the license: https://creativecommons.org/licenses/by-sa/4.0/legalcode. Print edition ordering details Links to collaborator portal and listserv Links to other books in the series Errata You must: Attribute — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. Suggested citation: Adapted by _[your name]_ from (c) Steven W. Ellingson, Electromagnetics, Vol 2, https://doi .org/10.21061/electromagnetics-vol-2, CC BY SA 4.0, https://creativecommons.org/licenses/by-sa/4.0. ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. You may not: Add any additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. If adapting or building upon, you are encouraged to: Incorporate only your own work or works with a CC BY or CC BY-SA license. Attribute all added content. Have your work peer reviewed. Include a transformation statement that describes changes, additions, accessibility features, and any subsequent peer review. If incorporating text or figures under an informed fair use analysis, mark them as such and cite them. Share your contributions in the collaborator portal or on the listserv. Contact the author to explore contributing your additions to the project. Suggestions for creating and adapting Create and share learning tools and study aids. Translate. Modify the sequence or structure. Add or modify problems and examples. Transform or build upon in other formats. Submit suggestions and comments Submit suggestions (anonymous): http://bit.ly/electromagnetics-suggestion Email: publishing@vt.edu Annotate using Hypothes.is http://web.hypothes.is For more information see the User Feedback Guide: http://bit.ly/userfeedbackguide Adaptation resources LaTeX source files are available. Adapt on your own at https://libretexts.org. Guide: Modifying an Open Textbook https://press.rebus.community/otnmodify.
Electromagnetics_Vol2_Page_6_Chunk2178
Contents Preface ix 1 Preliminary Concepts 1 1.1 Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3 Coordinate Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.4 Electromagnetic Field Theory: A Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2 Magnetostatics Redux 11 2.1 Lorentz Force . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Magnetic Force on a Current-Carrying Wire . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.3 Torque Induced by a Magnetic Field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.4 The Biot-Savart Law . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.5 Force, Energy, and Potential Difference in a Magnetic Field . . . . . . . . . . . . . . . . . . . 20 3 Wave Propagation in General Media 25 3.1 Poynting’s Theorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.2 Poynting Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.3 Wave Equations for Lossy Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 3.4 Complex Permittivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.5 Loss Tangent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 3.6 Plane Waves in Lossy Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 3.7 Wave Power in a Lossy Medium . . . . . . . . . . . . . . . . . . . . . . . .
Electromagnetics_Vol2_Page_7_Chunk2179
. . . . . . . . . 37 3.8 Decibel Scale for Power Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.9 Attenuation Rate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.10 Poor Conductors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.11 Good Conductors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.12 Skin Depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 4 Current Flow in Imperfect Conductors 48 4.1 AC Current Flow in a Good Conductor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.2 Impedance of a Wire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 4.3 Surface Impedance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 5 Wave Reflection and Transmission 56 5.1 Plane Waves at Normal Incidence on a Planar Boundary . . . . . . . . . . . . . . . . . . . . . 56 5.2 Plane Waves at Normal Incidence on a Material Slab . . . . . . . . . . . . . . . . . . . . . . 60 5.3 Total Transmission Through a Slab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 5.4 Propagation of a Uniform Plane Wave in an Arbitrary Direction . . . . . . . . . . . . . . . . . 67 vi
Electromagnetics_Vol2_Page_7_Chunk2180
CONTENTS vii 5.5 Decomposition of a Wave into TE and TM Components . . . . . . . . . . . . . . . . . . . . . 70 5.6 Plane Waves at Oblique Incidence on a Planar Boundary: TE Case . . . . . . . . . . . . . . . 72 5.7 Plane Waves at Oblique Incidence on a Planar Boundary: TM Case . . . . . . . . . . . . . . . 76 5.8 Angles of Reflection and Refraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 5.9 TE Reflection in Non-magnetic Media . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 5.10 TM Reflection in Non-magnetic Media . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 5.11 Total Internal Reflection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 5.12 Evanescent Waves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 6 Waveguides 95 6.1 Phase and Group Velocity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 6.2 Parallel Plate Waveguide: Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 6.3 Parallel Plate Waveguide: TE Case, Electric Field . . . . . . . . . . . . . . . . . . . . . . . . 99 6.4 Parallel Plate Waveguide: TE Case, Magnetic Field . . . . . . . . . . . . . . . . . . . . . . . 102 6.5 Parallel Plate Waveguide: TM Case, Electric Field . . . . . . . . . . . . . . . . . . . . . . . . 104 6.6 Parallel Plate Waveguide: The TM0 Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 6.7 General Relationships for Unidirectional Waves . . . . . . . . . . . . . . . . . . . . . . . . . 108 6.8 Rectangular Waveguide: TM Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 6.9 Rectangular Waveguide: TE Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 6.10 Rectangular Waveguide: Propagation Characteristics . . . . . . . . . . . . . . . . . . . . . . 117 7 Transmission Lines Redux 121 7.1 Parallel Wire Transmission Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Electromagnetics_Vol2_Page_8_Chunk2181
7.2 Microstrip Line Redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 7.3 Attenuation in Coaxial Cable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 7.4 Power Handling Capability of Coaxial Cable . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 7.5 Why 50 Ohms? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 8 Optical Fiber 138 8.1 Optical Fiber: Method of Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 8.2 Acceptance Angle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 8.3 Dispersion in Optical Fiber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 9 Radiation 145 9.1 Radiation from a Current Moment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 9.2 Magnetic Vector Potential . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 9.3 Solution of the Wave Equation for Magnetic Vector Potential . . . . . . . . . . . . . . . . . . 150 9.4 Radiation from a Hertzian Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 9.5 Radiation from an Electrically-Short Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 9.6 Far-Field Radiation from a Thin Straight Filament of Current . . . . . . . . . . . . . . . . . . 159 9.7 Far-Field Radiation from a Half-Wave Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . 161 9.8 Radiation from Surface and Volume Distributions of Current . . . . . . . . . . . . . . . . . . 162 10 Antennas 166 10.1 How Antennas Radiate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.2 Power Radiated by an Electrically-Short Dipole . . . . . . . . . . . . . . . . . . . . . . . . . 168 10.3 Power Dissipated by an Electrically-Short Dipole . . . . . . . . . . . . . . . . . . . . . . . .
Electromagnetics_Vol2_Page_8_Chunk2182
169 10.4 Reactance of the Electrically-Short Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 10.5 Equivalent Circuit Model for Transmission; Radiation Efficiency . . . . . . . . . . . . . . . . 173 10.6 Impedance of the Electrically-Short Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Electromagnetics_Vol2_Page_8_Chunk2183
viii CONTENTS 10.7 Directivity and Gain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 10.8 Radiation Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 10.9 Equivalent Circuit Model for Reception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 10.10 Reciprocity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 10.11 Potential Induced in a Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 10.12 Equivalent Circuit Model for Reception, Redux . . . . . . . . . . . . . . . . . . . . . . . . . 194 10.13 Effective Aperture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 10.14 Friis Transmission Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 A Constitutive Parameters of Some Common Materials 205 A.1 Permittivity of Some Common Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 A.2 Permeability of Some Common Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 A.3 Conductivity of Some Common Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 B Mathematical Formulas 209 B.1 Trigonometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 B.2 Vector Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 B.3 Vector Identities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 C Physical Constants 212 Index 213
Electromagnetics_Vol2_Page_9_Chunk2184
Preface About This Book [m0213] Goals for this book. This book is intended to serve as a primary textbook for the second semester of a two-semester course in undergraduate engineering electromagnetics. The presumed textbook for the first semester is Electromagnetics Vol. 1,1 which addresses the following topics: electric and magnetic fields; electromagnetic properties of materials; electromagnetic waves; and devices that operate according to associated electromagnetic principles including resistors, capacitors, inductors, transformers, generators, and transmission lines. The book you are now reading – Electromagnetics Vol. 2 – addresses the following topics: • Chapter 1 (“Preliminary Concepts”) provides a brief summary of conventions for units, notation, and coordinate systems, and a synopsis of electromagnetic field theory from Vol. 1. • Chapter 2 (“Magnetostatics Redux”) extends the coverage of magnetostatics in Vol. 1 to include magnetic forces, rudimentary motors, and the Biot-Savart law. • Chapter 3 (“Wave Propagation in General Media”) addresses Poynting’s theorem, theory of wave propagation in lossy media, and properties of imperfect conductors. • Chapter 4 (“Current Flow in Imperfect Conductors”) addresses the frequency-dependent distribution of current in wire conductors and subsequently the AC impedance of wires. 1S.W. Ellingson, Electromagnetics Vol. 1, VT Publishing, 2018. CC BY-SA 4.0. ISBN 9780997920185. https://doi.org/10.21061/electromagnetics-vol-1 • Chapter 5 (“Wave Reflection and Transmission”) addresses scattering of plane waves from planar interfaces. • Chapter 6 (“Waveguides”) provides an introduction to waveguide theory via the parallel plate and rectangular waveguides. • Chapter 7 (“Transmission Lines Redux”) extends the coverage of transmission lines in Vol. 1 to include parallel wire lines, the theory of microstrip lines, attenuation, and power-handling capabilities. The inevitable but hard-to-answer question “What’s so special about 50 Ω?” is addressed at the end of this chapter. • Chapter 8 (“Optical Fiber”) provides an introduction to multimode fiber optics, including the concepts of acceptance angle and modal dispersion. • Chapter 9 (“Radiation”) provides a derivation of the electromagnetic fields radiated by a current distribution, emphasizing the analysis of line distributions using the Hertzian dipole as a differential element. • Chapter 10 (“Antennas”) provides an introduction to antennas, emphasizing equivalent circuit models for transmission and reception and characterization in terms of directivity and pattern. This chapter concludes with the Friis transmission equation. Appendices covering material properties, mathematical formulas, and physical constants are repeated from Vol. 1, with a few additional items. Target audience. This book is intended for electrical engineering students in the third year of a bachelor of science degree program. It is assumed that students have successfully completed one semester of Electromagnetics Vol. 2. c⃝2020 S.W. Ellingson CC BY SA 4.0. https://doi.org/10.21061/electromagnetics-vol-2
Electromagnetics_Vol2_Page_10_Chunk2185
x PREFACE engineering electromagnetics, nominally using Vol. 1. However, the particular topics and sequence of topics in Vol. 1 are not an essential prerequisite, and in any event this book may be useful as a supplementary reference when a different textbook is used. It is assumed that readers are familiar with the fundamentals of electric circuits and linear systems, which are normally taught in the second year of the degree program. It is also assumed that readers are proficient in basic engineering mathematics, including complex numbers, trigonometry, vectors, partial differential equations, and multivariate calculus. Notation, examples, and highlights. Section 1.2 summarizes the mathematical notation used in this book. Examples are set apart from the main text as follows: Example 0.1. This is an example. “Highlight boxes” are used to identify key ideas as follows: This is a key idea. What are those little numbers in square brackets? This book is a product of the Open Electromagnetics Project. This project provides a large number of sections (“modules”) which are assembled (“remixed”) to create new and different versions of the book. The text “[m0213]” that you see at the beginning of this section uniquely identifies the module within the larger set of modules provided by the project. This identification is provided because different remixes of this book may exist, each consisting of a different subset and arrangement of these modules. Prospective authors can use this identification as an aid in creating their own remixes. Why do some sections of this book seem to repeat material presented in previous sections? In some remixes of this book, authors might choose to eliminate or reorder modules. For this reason, the modules are written to “stand alone” as much as possible. As a result, there may be some redundancy between sections that would not be present in a traditional (non-remixable) textbook. While this may seem awkward to some at first, there are clear benefits: In particular, it never hurts to review relevant past material before tackling a new concept. And, since the electronic version of this book is being offered at no cost, there is not much gained by eliminating this useful redundancy. Why cite Wikipedia pages as additional reading? Many modules cite Wikipedia entries as sources of additional information. Wikipedia represents both the best and worst that the Internet has to offer. Most educators would agree that citing Wikipedia pages as primary sources is a bad idea, since quality is variable and content is subject to change over time. On the other hand, many Wikipedia pages are excellent, and serve as useful sources of relevant information that is not strictly within the scope of the curriculum. Furthermore, students benefit from seeing the same material presented differently, in a broader context, and with the additional references available as links from Wikipedia pages. We trust instructors and students to realize the potential pitfalls of this type of resource and to be alert for problems. Acknowledgments. Here’s a list of talented and helpful people who contributed to this book: The staff of Virginia Tech Publishing, University Libraries, Virginia Tech: Acquisitions/Developmental Editor & Project Manager: Anita Walz Advisors: Peter Potter, Corinne Guimont Cover, Print Production: Robert Browder Other Virginia Tech contributors: Accessibility: Christa Miller, Corinne Guimont, Sarah Mease Assessment: Anita Walz Virginia Tech Students: Alt text writer: Michel Comer Figure designers: Kruthika Kikkeri, Sam Lally, Chenhao Wang Copyediting: Longleaf Press External reviewers: Randy Haupt, Colorado School of Mines Karl Warnick, Brigham Young University Anonymous faculty member, research university
Electromagnetics_Vol2_Page_11_Chunk2186
xi Also, thanks are due to the students of the Fall 2019 section of ECE3106 at Virginia Tech who used the beta version of this book and provided useful feedback. Finally, we acknowledge all those who have contributed their art to Wikimedia Commons (https://commons.wikimedia.org/) under open licenses, allowing their work to appear as figures in this book. These contributors are acknowledged in figures and in the “Image Credits” section at the end of each chapter. Thanks to each of you for your selfless effort. About the Open Electromagnetics Project [m0148] The Open Electromagnetics Project (https://www.faculty.ece.vt.edu/swe/oem/) was established at Virginia Tech in 2017 with the goal of creating no-cost openly-licensed textbooks for courses in undergraduate engineering electromagnetics. While a number of very fine traditional textbooks are available on this topic, we feel that it has become unreasonable to insist that students pay hundreds of dollars per book when effective alternatives can be provided using modern media at little or no cost to the student. This project is equally motivated by the desire for the freedom to adopt, modify, and improve educational resources. This work is distributed under a Creative Commons BY SA license which allows – and we hope encourages – others to adopt, modify, improve, and expand the scope of our work.
Electromagnetics_Vol2_Page_12_Chunk2187
xii PREFACE About the Author [m0153] Steven W. Ellingson (ellingson@vt.edu) is an Associate Professor at Virginia Tech in Blacksburg, Virginia, in the United States. He received PhD and MS degrees in Electrical Engineering from the Ohio State University and a BS in Electrical and Computer Engineering from Clarkson University. He was employed by the U.S. Army, Booz-Allen & Hamilton, Raytheon, and the Ohio State University ElectroScience Laboratory before joining the faculty of Virginia Tech, where he teaches courses in electromagnetics, radio frequency electronics, wireless communications, and signal processing. His research includes topics in wireless communications, radio science, and radio frequency instrumentation. Professor Ellingson serves as a consultant to industry and government and is the author of Radio Systems Engineering (Cambridge University Press, 2016) and Electromagnetics Vol. 1 (VT Publishing, 2018).
Electromagnetics_Vol2_Page_13_Chunk2188
Chapter 1 Preliminary Concepts 1.1 Units [m0072] The term “unit” refers to the measure used to express a physical quantity. For example, the mean radius of the Earth is about 6,371,000 meters; in this case, the unit is the meter. A number like “6,371,000” becomes a bit cumbersome to write, so it is common to use a prefix to modify the unit. For example, the radius of the Earth is more commonly said to be 6371 kilometers, where one kilometer is understood to mean 1000 meters. It is common practice to use prefixes, such as “kilo-,” that yield values in the range of 0.001 to 10, 000. A list of standard prefixes appears in Table 1.1. Prefix Abbreviation Multiply by: exa E 1018 peta P 1015 tera T 1012 giga G 109 mega M 106 kilo k 103 milli m 10−3 micro µ 10−6 nano n 10−9 pico p 10−12 femto f 10−15 atto a 10−18 Table 1.1: Prefixes used to modify units. Unit Abbreviation Quantifies: ampere A electric current coulomb C electric charge farad F capacitance henry H inductance hertz Hz frequency joule J energy meter m distance newton N force ohm Ω resistance second s time tesla T magnetic flux density volt V electric potential watt W power weber Wb magnetic flux Table 1.2: Some units that are commonly used in elec- tromagnetics. Writing out the names of units can also become tedious. For this reason, it is common to use standard abbreviations; e.g., “6731 km” as opposed to “6371 kilometers,” where “k” is the standard abbreviation for the prefix “kilo” and “m” is the standard abbreviation for “meter.” A list of commonly-used base units and their abbreviations are shown in Table 1.2. To avoid ambiguity, it is important to always indicate the units of a quantity; e.g., writing “6371 km” as opposed to “6371.” Failure to do so is a common source of error and misunderstandings. An example is the expression: l = 3t where l is length and t is time. It could be that l is in Electromagnetics Vol. 2. c⃝2020 S.W. Ellingson CC BY SA 4.0. https://doi.org/10.21061/electromagnetics-vol-2
Electromagnetics_Vol2_Page_14_Chunk2189
2 CHAPTER 1. PRELIMINARY CONCEPTS meters and t is in seconds, in which case “3” really means “3 m/s.” However, if it is intended that l is in kilometers and t is in hours, then “3” really means “3 km/h,” and the equation is literally different. To patch this up, one might write “l = 3t m/s”; however, note that this does not resolve the ambiguity we just identified – i.e., we still don’t know the units of the constant “3.” Alternatively, one might write “l = 3t where l is in meters and t is in seconds,” which is unambiguous but becomes quite awkward for more complicated expressions. A better solution is to write instead: l = (3 m/s) t or even better: l = at where a = 3 m/s since this separates the issue of units from the perhaps more-important fact that l is proportional to t and the constant of proportionality (a) is known. The meter is the fundamental unit of length in the International System of Units, known by its French acronym “SI” and sometimes informally referred to as the “metric system.” In this work, we will use SI units exclusively. Although SI is probably the most popular for engineering use overall, other systems remain in common use. For example, the English system, where the radius of the Earth might alternatively be said to be about 3959 miles, continues to be used in various applications and to a lesser or greater extent in various regions of the world. An alternative system in common use in physics and material science applications is the CGS (“centimeter-gram-second”) system. The CGS system is similar to SI, but with some significant differences. For example, the base unit of energy in the CGS system is not the “joule” but rather the “erg,” and the values of some physical constants become unitless. Therefore – once again – it is very important to include units whenever values are stated. SI defines seven fundamental units from which all other units can be derived. These fundamental units are distance in meters (m), time in seconds (s), current in amperes (A), mass in kilograms (kg), temperature in kelvin (K), particle count in moles (mol), and luminosity in candela (cd). SI units for electromagnetic quantities such as coulombs (C) for charge and volts (V) for electric potential are derived from these fundamental units. A frequently-overlooked feature of units is their ability to assist in error-checking mathematical expressions. For example, the electric field intensity may be specified in volts per meter (V/m), so an expression for the electric field intensity that yields units of V/m is said to be “dimensionally correct” (but not necessarily correct), whereas an expression that cannot be reduced to units of V/m cannot be correct. Additional Reading: • “International System of Units” on Wikipedia. • “Centimetre-gram-second system of units” on Wikipedia.
Electromagnetics_Vol2_Page_15_Chunk2190
1.2. NOTATION 3 1.2 Notation [m0005] The list below describes notation used in this book. • Vectors: Boldface is used to indicate a vector; e.g., the electric field intensity vector will typically appear as E. Quantities not in boldface are scalars. When writing by hand, it is common to write “E” or “−→ E ” in lieu of “E.” • Unit vectors: A circumflex is used to indicate a unit vector; i.e., a vector having magnitude equal to one. For example, the unit vector pointing in the +x direction will be indicated as ˆx. In discussion, the quantity “ˆx” is typically spoken “x hat.” • Time: The symbol t is used to indicate time. • Position: The symbols (x, y, z), (ρ, φ, z), and (r, θ, φ) indicate positions using the Cartesian, cylindrical, and spherical coordinate systems, respectively. It is sometimes convenient to express position in a manner which is independent of a coordinate system; in this case, we typically use the symbol r. For example, r = ˆxx + ˆyy + ˆzz in the Cartesian coordinate system. • Phasors: A tilde is used to indicate a phasor quantity; e.g., a voltage phasor might be indicated as eV , and the phasor representation of E will be indicated as eE. • Curves, surfaces, and volumes: These geometrical entities will usually be indicated in script; e.g., an open surface might be indicated as S and the curve bounding this surface might be indicated as C. Similarly, the volume enclosed by a closed surface S may be indicated as V. • Integrations over curves, surfaces, and volumes will usually be indicated using a single integral sign with the appropriate subscript. For example: Z C · · · dl is an integral over the curve C Z S · · · ds is an integral over the surface S Z V · · · dv is an integral over the volume V. • Integrations over closed curves and surfaces will be indicated using a circle superimposed on the integral sign. For example: I C · · · dl is an integral over the closed curve C I S ··· ds is an integral over the closed surface S A “closed curve” is one which forms an unbroken loop; e.g., a circle. A “closed surface” is one which encloses a volume with no openings; e.g., a sphere. • The symbol “∼=” means “approximately equal to.” This symbol is used when equality exists, but is not being expressed with exact numerical precision. For example, the ratio of the circumference of a circle to its diameter is π, where π ∼= 3.14. • The symbol “≈” also indicates “approximately equal to,” but in this case the two quantities are unequal even if expressed with exact numerical precision. For example, ex = 1 + x + x2/2 + ... as an infinite series, but ex ≈1 + x for x ≪1. Using this approximation, e0.1 ≈1.1, which is in good agreement with the actual value e0.1 ∼= 1.1052. • The symbol “∼” indicates “on the order of,” which is a relatively weak statement of equality indicating that the indicated quantity is within a factor of 10 or so of the indicated value. For example, µ ∼105 for a class of iron alloys, with exact values being larger or smaller by a factor of 5 or so. • The symbol “≜” means “is defined as” or “is equal as the result of a definition.” • Complex numbers: j ≜√−1. • See Appendix C for notation used to identify commonly-used physical constants.
Electromagnetics_Vol2_Page_16_Chunk2191
4 CHAPTER 1. PRELIMINARY CONCEPTS 1.3 Coordinate Systems [m0180] The coordinate systems most commonly used in engineering analysis are the Cartesian, cylindrical, and spherical systems. These systems are illustrated in Figures 1.1, 1.2, and 1.3, respectively. Note that the use of variables is not universal; in particular, it is common to encounter the use of r in lieu of ρ for the radial coordinate in the cylindrical system, and the use of R in lieu of r for the radial coordinate in the spherical system. Additional Reading: • “Cylindrical coordinate system” on Wikipedia. • “Spherical coordinate system” on Wikipedia. y x z y x z c⃝K. Kikkeri CC BY SA 4.0 Figure 1.1: Cartesian coordinate system. y x ϕ z ρ ϕ z ρ z c⃝K. Kikkeri CC BY SA 4.0 Figure 1.2: Cylindrical coordinate system. y x ϕ z r θ θ ϕ r c⃝K. Kikkeri CC BY SA 4.0 Figure 1.3: Spherical coordinate system.
Electromagnetics_Vol2_Page_17_Chunk2192
1.4. ELECTROMAGNETIC FIELD THEORY: A REVIEW 5 1.4 Electromagnetic Field Theory: A Review [m0179] This book is the second in a series of textbooks on electromagnetics. This section presents a summary of electromagnetic field theory concepts presented in the previous volume. Electric charge and current. Charge is the ultimate source of the electric field and has SI base units of coulomb (C). An important source of charge is the electron, whose charge is defined to be negative. However, the term “charge” generally refers to a large number of charge carriers of various types, and whose relative net charge may be either positive or negative. Distributions of charge may alternatively be expressed in terms of line charge density ρl (C/m), surface charge density ρs (C/m2), or volume charge density ρv (C/m3). Electric current describes the net motion of charge. Current is expressed in SI base units of amperes (A) and may alternatively be quantified in terms of surface current density Js (A/m) or volume current density J (A/m2). Electrostatics. Electrostatics is the theory of the electric field subject to the constraint that charge does not accelerate. That is, charges may be motionless (“static”) or move without acceleration (“steady current”). The electric field may be interpreted in terms of energy or flux. The energy interpretation of the electric field is referred to as electric field intensity E (SI base units of N/C or V/m), and is related to the energy associated with charge and forces between charges. One finds that the electric potential (SI base units of V) over a path C is given by V = − Z C E · dl (1.1) The principle of independence of path means that only the endpoints of C in Equation 1.1, and no other details of C, matter. This leads to the finding that the electrostatic field is conservative; i.e., I C E · dl = 0 (1.2) This is referred to as Kirchoff’s voltage law for electrostatics. The inverse of Equation 1.1 is E = −∇V (1.3) That is, the electric field intensity points in the direction in which the potential is most rapidly decreasing, and the magnitude is equal to the rate of change in that direction. The flux interpretation of the electric field is referred to as electric flux density D (SI base units of C/m2), and quantifies the effect of charge as a flow emanating from the charge. Gauss’ law for electric fields states that the electric flux through a closed surface is equal to the enclosed charge Qencl; i.e., I S D · ds = Qencl (1.4) Within a material region, we find D = ǫE (1.5) where ǫ is the permittivity (SI base units of F/m) of the material. In free space, ǫ is equal to ǫ0 ≜8.854 × 10−12 F/m (1.6) It is often convenient to quantify the permittivity of material in terms of the unitless relative permittivity ǫr ≜ǫ/ǫ0. Both E and D are useful as they lead to distinct and independent boundary conditions at the boundary between dissimilar material regions. Let us refer to these regions as Regions 1 and 2, having fields (E1, D1) and (E2, D2), respectively. Given a vector ˆn perpendicular to the boundary and pointing into Region 1, we find ˆn × [E1 −E2] = 0 (1.7) i.e., the tangential component of the electric field is continuous across a boundary, and ˆn · [D1 −D2] = ρs (1.8) i.e., any discontinuity in the normal component of the electric field must be supported by a surface charge distribution on the boundary.
Electromagnetics_Vol2_Page_18_Chunk2193
6 CHAPTER 1. PRELIMINARY CONCEPTS Magnetostatics. Magnetostatics is the theory of the magnetic field in response to steady current or the intrinsic magnetization of materials. Intrinsic magnetization is a property of some materials, including permanent magnets and magnetizable materials. Like the electric field, the magnetic field may be quantified in terms of energy or flux. The flux interpretation of the magnetic field is referred to as magnetic flux density B (SI base units of Wb/m2), and quantifies the field as a flow associated with, but not emanating from, the source of the field. The magnetic flux Φ (SI base units of Wb) is this flow measured through a specified surface. Gauss’ law for magnetic fields states that I S B · ds = 0 (1.9) i.e., the magnetic flux through a closed surface is zero. Comparison to Equation 1.4 leads to the conclusion that the source of the magnetic field cannot be localized; i.e., there is no “magnetic charge” analogous to electric charge. Equation 1.9 also leads to the conclusion that magnetic field lines form closed loops. The energy interpretation of the magnetic field is referred to as magnetic field intensity H (SI base units of A/m), and is related to the energy associated with sources of the magnetic field. Ampere’s law for magnetostatics states that I C H · dl = Iencl (1.10) where Iencl is the current flowing past any open surface bounded by C. Within a homogeneous material region, we find B = µH (1.11) where µ is the permeability (SI base units of H/m) of the material. In free space, µ is equal to µ0 ≜4π × 10−7 H/m. (1.12) It is often convenient to quantify the permeability of material in terms of the unitless relative permeability µr ≜µ/µ0. Both B and H are useful as they lead to distinct and independent boundary conditions at the boundaries between dissimilar material regions. Let us refer to these regions as Regions 1 and 2, having fields (B1, H1) and (B2, H2), respectively. Given a vector ˆn perpendicular to the boundary and pointing into Region 1, we find ˆn · [B1 −B2] = 0 (1.13) i.e., the normal component of the magnetic field is continuous across a boundary, and ˆn × [H1 −H2] = Js (1.14) i.e., any discontinuity in the tangential component of the magnetic field must be supported by current on the boundary. Maxwell’s equations. Equations 1.2, 1.4, 1.9, and 1.10 are Maxwell’s equations for static fields in integral form. As indicated in Table 1.3, these equations may alternatively be expressed in differential form. The principal advantage of the differential forms is that they apply at each point in space (as opposed to regions defined by C or S), and subsequently can be combined with the boundary conditions to solve complex problems using standard methods from the theory of differential equations. Conductivity. Some materials consist of an abundance of electrons which are loosely-bound to the atoms and molecules comprising the material. The force exerted on these electrons by an electric field may be sufficient to overcome the binding force, resulting in motion of the associated charges and subsequently current. This effect is quantified by Ohm’s law for electromagnetics: J = σE (1.15) where J in this case is the conduction current determined by the conductivity σ (SI base units of S/m). Conductivity is a property of a material that ranges from negligible (i.e., for “insulators”) to very large for good conductors, which includes most metals. A perfect conductor is a material within which E is essentially zero regardless of J. For such material, σ →∞. Perfect conductors are said to be equipotential regions; that is, the potential difference
Electromagnetics_Vol2_Page_19_Chunk2194
1.4. ELECTROMAGNETIC FIELD THEORY: A REVIEW 7 Electrostatics / Time-Varying Magnetostatics (Dynamic) Electric & magnetic independent possibly coupled fields are... Maxwell’s eqns. H S D · ds = Qencl H S D · ds = Qencl (integral) H C E · dl = 0 H C E · dl = −∂ ∂t R S B · ds H S B · ds = 0 H S B · ds = 0 H C H · dl = Iencl H C H · dl = Iencl+ R S ∂ ∂tD · ds Maxwell’s eqns. ∇· D = ρv ∇· D = ρv (differential) ∇× E = 0 ∇× E = −∂ ∂tB ∇· B = 0 ∇· B = 0 ∇× H = J ∇× H = J+ ∂ ∂tD Table 1.3: Comparison of Maxwell’s equations for static and time-varying electromagnetic fields. Differences in the time-varying case relative to the static case are highlighted in blue. between any two points within a perfect conductor is zero, as can be readily verified using Equation 1.1. Time-varying fields. Faraday’s law states that a time-varying magnetic flux induces an electric potential in a closed loop as follows: V = −∂ ∂tΦ (1.16) Setting this equal to the left side of Equation 1.2 leads to the Maxwell-Faraday equation in integral form: I C E · dl = −∂ ∂t Z S B · ds (1.17) where C is the closed path defined by the edge of the open surface S. Thus, we see that a time-varying magnetic flux is able to generate an electric field. We also observe that electric and magnetic fields become coupled when the magnetic flux is time-varying. An analogous finding leads to the general form of Ampere’s law: I C H · dl = Iencl + Z S ∂ ∂tD · ds (1.18) where the new term is referred to as displacement current. Through the displacement current, a time-varying electric flux may be a source of the magnetic field. In other words, we see that the electric and magnetic fields are coupled when the electric flux is time-varying. Gauss’ law for electric and magnetic fields, boundary conditions, and constitutive relationships (Equations 1.5, 1.11, and 1.15) are the same in the time-varying case. As indicated in Table 1.3, the time-varying version of Maxwell’s equations may also be expressed in differential form. The differential forms make clear that variations in the electric field with respect to position are associated with variations in the magnetic field with respect to time (the Maxwell-Faraday equation), and vice-versa (Ampere’s law). Time-harmonic waves in source-free and lossless media. The coupling between electric and magnetic fields in the time-varying case leads to wave phenomena. This is most easily analyzed for fields which vary sinusoidally, and may thereby be expressed as phasors.1 Phasors, indicated in this book by the tilde (“e”), are complex-valued quantities representing the magnitude and phase of the associated sinusoidal waveform. Maxwell’s equations in differential phasor form are: ∇· eD = eρv (1.19) ∇× eE = −jω eB (1.20) ∇· eB = 0 (1.21) ∇× eH = eJ + jω eD (1.22) where ω ≜2πf, and where f is frequency (SI base 1Sinusoidally-varying fields are sometimes also said to be time- harmonic.
Electromagnetics_Vol2_Page_20_Chunk2195
8 CHAPTER 1. PRELIMINARY CONCEPTS units of Hz). In regions which are free of sources (i.e., charges and currents) and consisting of loss-free media (i.e., σ = 0), these equations reduce to the following: ∇· eE = 0 (1.23) ∇× eE = −jωµ eH (1.24) ∇· eH = 0 (1.25) ∇× eH = +jωǫeE (1.26) where we have used the relationships D = ǫE and B = µH to eliminate the flux densities D and B, which are now redundant. Solving Equations 1.23–1.26 for E and H, we obtain the vector wave equations: ∇2 eE + β2 eE = 0 (1.27) ∇2 eH + β2 eH = 0 (1.28) where β ≜ω√µǫ (1.29) Waves in source-free and lossless media are solutions to the vector wave equations. Uniform plane waves in source-free and lossless media. An important subset of solutions to the vector wave equations are uniform plane waves. Uniform plane waves result when solutions are constrained to exhibit constant magnitude and phase in a plane. For example, if this plane is specified to be perpendicular to z (i.e., ∂/∂x = ∂/∂y = 0) then solutions for eE have the form: eE = ˆx eEx + ˆy eEy (1.30) where eEx = E+ x0e−jβz + E− x0e+jβz (1.31) eEy = E+ y0e−jβz + E− y0e+jβz (1.32) and where E+ x0, E− x0, E+ y0, and E− y0 are constant complex-valued coefficients which depend on sources and boundary conditions. The first term and second terms of Equations 1.31 and 1.32 correspond to waves traveling in the +ˆz and −ˆz directions, respectively. Because eH is a solution to the same vector wave equation, the solution for H is identical except with different coefficients. The scalar components of the plane waves described in Equations 1.31 and 1.32 exhibit the same characteristics as other types of waves, including sound waves and voltage and current waves in transmission lines. In particular, the phase velocity of waves propagating in the +ˆz and −ˆz direction is vp = ω β = 1 √µǫ (1.33) and the wavelength is λ = 2π β (1.34) By requiring solutions for eE and eH to satisfy the Maxwell curl equations (i.e., the Maxwell-Faraday equation and Ampere’s law), we find that eE, eH, and the direction of propagation ˆk are mutually perpendicular. In particular, we obtain the plane wave relationships: eE = −ηˆk × eH (1.35) eH = 1 η ˆk × eE (1.36) where η ≜ rµ ǫ (1.37) is the wave impedance, also known as the intrinsic impedance of the medium, and ˆk is in the same direction as eE × eH. The power density associated with a plane wave is S = eE 2 2η (1.38) where S has SI base units of W/m2, and here it is assumed that eE is in peak (as opposed to rms) units. Commonly-assumed properties of materials. Finally, a reminder about commonly-assumed properties of the material constitutive parameters ǫ, µ, and σ. We often assume these parameters exhibit the following properties: • Homogeneity. A material that is homogeneous is uniform over the space it occupies; that is, the values of its constitutive parameters are constant at all locations within the material.
Electromagnetics_Vol2_Page_21_Chunk2196
1.4. ELECTROMAGNETIC FIELD THEORY: A REVIEW 9 • Isotropy. A material that is isotropic behaves in precisely the same way regardless of how it is oriented with respect to sources, fields, and other materials. • Linearity. A material is said to be linear if its properties do not depend on the sources and fields applied to the material. Linear media exhibit superposition; that is, the response to multiple sources is equal to the sum of the responses to the sources individually. • Time-invariance. A material is said to be time-invariant if its properties do not vary as a function of time. Additional Reading: • “Maxwell’s Equations” on Wikipedia. • “Wave Equation” on Wikipedia. • “Electromagnetic Wave Equation” on Wikipedia. • “Electromagnetic radiation” on Wikipedia. [m0181]
Electromagnetics_Vol2_Page_22_Chunk2197
10 CHAPTER 1. PRELIMINARY CONCEPTS Image Credits Fig. 1.1: c⃝K. Kikkeri, https://commons.wikimedia.org/wiki/File:M0006 fCartesianBasis.svg, CC BY SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). Fig. 1.2: c⃝K. Kikkeri, https://commons.wikimedia.org/wiki/File:M0096 fCylindricalCoordinates.svg, CC BY SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). Fig. 1.3: c⃝K. Kikkeri, https://commons.wikimedia.org/wiki/File:Spherical Coordinate System.svg, CC BY SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/).
Electromagnetics_Vol2_Page_23_Chunk2198
Chapter 2 Magnetostatics Redux 2.1 Lorentz Force [m0015] The Lorentz force is the force experienced by charge in the presence of electric and magnetic fields. Consider a particle having charge q. The force Fe experienced by the particle in the presence of electric field intensity E is Fe = qE The force Fm experienced by the particle in the presence of magnetic flux density B is Fm = qv × B where v is the velocity of the particle. The Lorentz force experienced by the particle is simply the sum of these forces; i.e., F = Fe + Fm = q (E + v × B) (2.1) The term “Lorentz force” is simply a concise way to refer to the combined contributions of the electric and magnetic fields. A common application of the Lorentz force concept is in analysis of the motions of charged particles in electromagnetic fields. The Lorentz force causes charged particles to exhibit distinct rotational (“cyclotron”) and translational (“drift”) motions. This is illustrated in Figures 2.1 and 2.2. Additional Reading: • “Lorentz force” on Wikipedia. c⃝Stannered CC BY 2.5. Figure 2.1: Motion of a particle bearing (left) posi- tive charge and (right) negative charge. Top: Magnetic field directed toward the viewer; no electric field. Bot- tom: Magnetic field directed toward the viewer; elec- tric field oriented as shown. Electromagnetics Vol. 2. c⃝2020 S.W. Ellingson CC BY SA 4.0. https://doi.org/10.21061/electromagnetics-vol-2
Electromagnetics_Vol2_Page_24_Chunk2199
12 CHAPTER 2. MAGNETOSTATICS REDUX c⃝M. Biaek CC BY-SA 4.0. Figure 2.2: Electrons moving in a circle in a magnetic field (cyclotron motion). The electrons are produced by an electron gun at bottom, consisting of a hot cath- ode, a metal plate heated by a filament so it emits elec- trons, and a metal anode at a high voltage with a hole which accelerates the electrons into a beam. The elec- trons are normally invisible, but enough air has been left in the tube so that the air molecules glow pink when struck by the fast-moving electrons. 2.2 Magnetic Force on a Current-Carrying Wire [m0017] Consider an infinitesimally-thin and perfectly-conducting wire bearing a current I (SI base units of A) in free space. Let B (r) be the impressed magnetic flux density at each point r in the region of space occupied by the wire. By impressed, we mean that the field exists in the absence of the current-carrying wire, as opposed to the field that is induced by this current. Since current consists of charged particles in motion, we expect that B(r) will exert a force on the current. Since the current is constrained to flow on the wire, we expect this force will also be experienced by the wire. Let us now consider this force. To begin, recall that the force exerted on a particle bearing charge q having velocity v is Fm (r) = qv (r) × B (r) (2.2) Thus, the force exerted on a differential amount of charge dq is dFm (r) = dq v (r) × B (r) (2.3) Let dl (r) represent a differential-length segment of the wire at r, pointing in the direction of current flow. Then dq v (r) = Idl (r) (2.4) (If this is not clear, it might help to consider the units: On the left, C·m/s = (C/s)·m = A·m, as on the right.) Subsequently, dFm (r) = Idl (r) × B (r) (2.5) There are three important cases of practical interest. First, consider a straight segment l forming part of a closed loop of current in a spatially-uniform impressed magnetic flux density B (r) = B0. In this case, the force exerted by the magnetic field on such a segment is given by Equation 2.5 with dl replaced by l; i.e.: Fm = Il × B0 (2.6) Summarizing, The force experienced by a straight segment of current-carrying wire in a spatially-uniform mag- netic field is given by Equation 2.6. The second case of practical interest is a rigid closed loop of current in a spatially-uniform magnetic flux density B0. If the loop consists of straight sides – e.g., a rectangular loop – then the force applied to the loop is the sum of the forces applied to each side separately, as determined by Equation 2.6. However, we wish to consider loops of arbitrary shape. To accommodate arbitrarily-shaped loops, let C be the path through space occupied by the loop. Then the force experienced by the loop is F = Z C dFm (r) = Z C Idl (r) × B0 (2.7) Since I and B0 are constants, they may be extracted from the integral: F = I Z C dl (r)  × B0 (2.8) Note the quantity in square brackets is zero. Therefore:
Electromagnetics_Vol2_Page_25_Chunk2200