Archive for the 'PHP tutorial scripts' Category

Logic and Operators

PHP supports a wide range of operators. The complete set can be found by searching the PHP manual. If you go to the manual online, you’ll find that operators have their own section in the language reference portion:

{show the cursor using the PHP manual online – documentation -> English -> Operators}

I’m going to cover just 4 types of operators in this video, but if you want to learn more, they’re covered very well in the online manual.

The first set of operators we’re going to cover are the arithmetic operators. These include the familiar operators for addition, subtraction, multiplication, and division, plus 2 others – negation and modulus. The multiplication sign in PHP is the asterisk character ‘*’, and the division sign is the forward slash ‘/’. If you use division on two integers that don’t divide evenly, your result will be a float. However, if you use division on two ints that do divide evenly, your result is an int. This is worth pointing out, because in some languages, dividing ints just cuts off anything after the decimal in order to keep the result as an int. And in some other languages, they’ll cast the result of an integer division to a float no matter whether they divide evenly or not. The PHP engineers decided on a middle way.

As for negation, it’s just the minus sign in front of a variable to get its sign opposite. So, in the expression:

$a = 5;
$b = -$a;

$b becomes -5. And:

$c = -$b;

$c becomes 5.

Modulus is just a little more complicated. It’s used to find the remainder left over from dividing two numbers. So for instance:

$a = 25 % 3;

The way this works is you take 25 and subtract as many 3’s as you can without going negative. Whatever is left is the result of your expression. In this case, that’s 25-24, which is 1. So $a has a value of 1. Now, if the first number in your expression had been ‘-25’ your result would be -1. Although, oddly enough, the sign of the number after the modulus operator makes no difference to the sign of the result. So if it had been 25 % -3 the value of the expression would still be a 1.

As far as operator precedence goes, negation has the highest precedence. Multiplication, division, and modulus all have the same precedence. And addition and subtraction together have the lowest precedence. Don’t dwell too much on it right now though, since we tackle PHP’s ability to do math in a later chapter. I’m only introducing this now because it’s just handy to be able to do a little basic arithmetic here and there in your everyday scripts.

The next type of operator we’re going to look at is the assignment operator. The basic assignment operator is just the ‘=’ sign, as we’ve already seen in previous videos. It simply assigns the value of the expression to the right of the equal sign to a variable of some sort on the left side.

There are other assignment operators though. They all boil down to something like ‘Perform an action on the variable to the left and then assign the result of that expression back to the left-hand variable.’

So, for instance, there’s an operator for incrementing your variable by some amount. Now, you could write:

$a = $a + 5;

Since it evaluates the right-hand side first, the value of $a is incremented by 5. However, PHP provides another way to do the same thing in a sort of short-hand:

$a += 5;

PHP also has assignment operators for subtraction, multiplication, division, and modulus:

$a -= 5; //produces the exact same result as $a = $a – 5;
$a *= 3; //produces the exact same result as $a = $a * 3;
$a /= 2; //produces the exact same result as $a = $a / 2;
$a %= 8; //produces the exact same result as $a = $a % 8;

If all you need is to increment or decrement a variable’s value by one, PHP supports another, even shorter, short-hand:

$a++; //identical to $a += 1 and $a = $a + 1
$a–;  //identical to $a -= 1 and $a = $a – 1

The next type of operator we’ll look at are the comparison operators. These are the ones that you use when you want to compare two expressions in some way, and arrive at a value for the combined expression of either true or false.

When you want to determine whether two expressions are alike, PHP provides both an equality comparison and an identity comparison. The difference is important. For an equality test, the operator is two equal signs next to each other, like this:

$a == $b;

If $a and $b have the same value, the expression returns true. But they may not be the same thing. For instance:

$a = 1;
$b = ‘1’;
$c = $a == $b; //$c is true, because converting 1 to a string produces ‘1’ and converting ‘1’ to an int produces 1

In this case $c will hold the value ‘true’, because that’s the result of the equality test. But if we change to the identity test, which consists of 3 equal signs together, we’ll get false, because the identity test checks both the value and the type:

$c = $a === $b; //$c is now false because while they have the same value, $a and $b are not of the same type

This test is particularly useful when, for instance, a function might return 0 or false, and you need to be  sure you know which one you got back. For instance, PHP provides a useful built in function called strpos. It searches one string for the first occurrence of another. If it finds that search term at the very beginning of the searched string, it returns a 0. But if it doesn’t find the term at all, it returns the boolean false. Just testing for == false would be a recipe for trouble down the line.

Now, the counterpart to the equality and identity operators are the inequality and non-identity operators. These are an exclamation point followed by an equal sign, and an exclamation point followed by two equal signs, respectively.

$a != $b; //test for different value
$a !== $b; //test for different value or type

This has different meanings for different types. A string and an int can be equal if they have the same quoted value. But a string and an int can never be identical, because they’re of different types. If two ints are equal, they are also identical. And the same is true for strings and booleans. However, for arrays, two arrays are equal if they have the same key/value pairs. But those values can be of different types so long as they pass an equality test with each other. Two arrays are only identical if they have identical key/value pairs (meaning types are also the same), and with all key/value pairs in the same order.

The remaining comparison operators are the greater than/less than operators:

$a < $b; //test whether $a is less than $b
$a > $b; //test whether $a is greater than $b
$a <= $b; //test whether $a is either less than or equal to $b
$a >= $b; //test whether $a is greater than or equal to $b

With ints, the comparison is obvious enough. You’re just checking basic math. With strings, you’r checking them alphabetically, so a string starting with an ‘a’ would be considered less than a string starting with a ‘b’. However, the comparison is also case-sensitive. So a string beginning with lower-case ‘a’ would be considered greater than a string beginning with an upper-case ‘B’. If you need to compare strings in a case-insensitive way, PHP provides some built in functions to do that. We look at those more in another chapter.  With booleans, ‘false’ is less than ‘true’. And with arrays, well, it gets difficult to explain, and it’s not something you’re likely to need to do anyway.

The last operators we’re going to take a quick look at are the logical operators. And we’re only going to look at 3 of them. These are called logical operators because they’re supposed to be used with boolean logic expressions. The first, is the ‘not’ operator. It’s just a single exclamation point places in front of that expression, and all it does is flip the expression. If the expression had been true before, with the not operator it becomes false. And if it had been false before, the not operator makes it true.

The second operator is the ‘and’ operator. It consists of 2 ampersands together. You use it to string two boolean expressions together. If they were both true, the entire combined expression becomes true. But if either or both expression had been false, the combined expression is false.

$a = true && false; //evaluates to false
$a = true && true; //evaluates to true

The way the PHP engine works is by evaluating statements from left to right. If the left expression is false, it doesn’t even bother to evaluate the right-hand expression. It just returns false and skips the code to the right. You can prove this is the case by putting some code to the right that ought to cause some sort of run-time error, and code to the left that will evaluate to false:

false && array() + 5; //$a is false – no error
true && array() + 5; //throws a fatal error for unsupported operand types

The counterpart to the and operator is the or operator. It consists of two vertical bars ‘||’. If an expression on either side of the or operator evaluates to true, then the entire expression is true:

true || false; //evaluates to true
false || false; //evaluate to false

And just like the and operator will stop evaluating an expression if the first half is false, the or operator will stop evaluating an expression if the first half is true. In that case it just returns true and the second half of the expression is simply ignored.

Those are all the operators I wanted to cover in this video, but there are plenty more provided by PHP. You won’t need them to complete any of the exercises at the end of this chapter, but if you want to learn them just in case you need them in the future, as always, I refer you back to the PHP manual.

{show website http://us2.php.net/manual/en/language.operators.php}

February 07 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on Logic and Operators

PHP Arrays

An array is a data structure for grouping values. Each value is associated with a key that can be used to reference it. Arrays are pretty common across programming languages, but PHP arrays have some quirks that can sometimes throw a new programmer off.

For one thing, since PHP is so loosely typed, you can define a variable as an array just by starting to use it as one. For another, PHP arrays can hold mixed types. That means an array can hold objects, integers, strings, booleans, even other arrays. And PHP arrays can expand as needed. There’s no need to declare in advance how big an array is or take any special action to increase its size once you start using it. And PHP supports both numerically-indexed arrays and associative arrays – that is, arrays that have strings for keys.

Let’s start by looking at the basic array creation syntax:

$a1 = array();

The function ‘array’ is actually a language construct. When it’s called this way, it generates a new, empty array, and assigns it to the variable $a1. In order to add values to it, you use square brackets. Here’s one way to do that:

$a1[] = 5;

In this case, the array gets the value 5. And since no key was specified, it automatically just gets the next number based on a 0-indexed sequence. Since in this case the 5 is the first value in the array, it gets assigned to the first index 0. If I want, I can specify the key for an element I add:

$a1[3] = 10;

And now the array has 2 elements. The key 0 refers to the value 5 and the key 3 refers to the value 10. Now, if I go back and use empty brackets again, like this:

$a1[] = ‘next’;

The PHP engine looks at the highest integer key already being used, and sets the value ‘next’ to an integer key that’s one number higher. So, $a1 now holds the value ‘next’ at the key 4.

Now, if I want to do these steps in one line, the array function lets us do that. All I have to do is:

$a1 = array(5, 3=>10, ‘next’);

The values are added to an array using a comma-separated list. Also, notice the double-arrow. That’s how you specify the key for a particular value.

We can also use string keys. When you do that, you’re making an associative array. Performance-wise, associative arrays are just a little slower than arrays that use numeric indexes, but you can gain a lot when it comes time to access your values, since associative arrays allow you to assign meaningful names to your array’s keys.

Here’s an example of using a string as an array key:

$a2 = array(‘joe’=>’orange’, ‘anne’=>’peach’, ‘phil’=>’banana’);
$a2[‘sandy’] = ‘apple’;

When it comes time to access the values in an array, we turn to the square bracket syntax again:

echo $a2[‘anne’]; //prints out ‘peach’

As far as keys, only ints or strings can be used. Other data types won’t work. If you want to have an array inside an array, that’s easy to do:

$a3 = array(‘first’ => array(4, 5, ‘hello’=>’world’), ‘second’=>array($a1, $a2));

If I want to access one of the inner array’s values, I need to use more than one set of square brackets:

echo $a3[‘first’][‘hello’]; //prints out ‘world’

You can embed arrays as many layers deep as you want.

Another important point about PHP arrays is that PHP supports array addition. For example:

$a4 = $a1 + $a2;

$a4 becomes a combination of $array1 and $array2. When used this way, the plus sign is referred to as the array union operator. If 2 arrays have the same keys, whether integer keys or string keys, the latter array’s duplicate value won’t show up in the union of the two, only the first array’s value with that key will be present.

If you try to add an array and a non-array though, the PHP engine will throw a fatal error, because the addition operator requires that both the operands (the expressions on either side of the plus sign) be of the same supported type.

That’s enough information to get you started using arrays. Later, we’re going to take a look at the vast number of built-in PHP functions that you can use with your arrays.

February 06 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on PHP Arrays

PHP Variable Types

PHP variables are loosely-typed, so a variable’s type isn’t really defined until you assign a value to it. Prior to that, all variables have the special type ‘null’, which is just a way of saying no type and no value. Once you give a variable a value, it also gets a type. PHP supports 7 types, besides null, but for most of this title, we’re really only going to look at 4 of them:

int – these are your counting numbers
string – any sequence of characters inside single or double quotes
array – a set of things that can be referenced individually or as a group
boolean – true or false

In addition to those types, PHP also supports floats, objects, and resources and these get covered in detail later in this tutorial. But those first 4 types are the most important to learn here at the beginning, and will probably make up more than 90% of the variables you use in your everyday coding, at least for a while.

In order to determine a variable’s type, PHP provides a special function called ‘gettype’. Here it is in action:

echo gettype($var1); //assuming $var1 isn’t defined anywhere, this will print ‘NULL’

$var1 = ‘I am a string’;
echo gettype($var1); //prints ‘string’

$var1 = 55;
echo gettype($var1); //prints ‘int’

$var1 = array(55, 60);
echo gettype($var1); //prints ‘array’

$var1 = true;
echo gettype($var1); //prints ‘boolean’

{show output}

Now, if you have a variable of one type, but you need to use it a variable of a different type, you can do what’s called a cast. You do this by putting the desired variable type in parenthesis in front of the variable you want to convert. Here’s how it works.

Suppose I have a variable that’s an int:

$var1 = 56;

If I cast it to a string, it becomes:

$var2 = (string)$var1; //now the string ’56’

It’s now a string, made up of the characters 5 and 6. This is significant because text is stored differently than ints. They might print out the same on the screen, but to the server, it sees an int as the binary representation of the number 56. With strings though, it sees a separate binary representation for each character, and these have to be linked together in some way that preserves information about those characters’ order. So it takes a bit more memory to store the string ’56’ than the int 56.

If you want to cast your variable as an array, here’s what you do:

$var2 = (array)$var1;

In this case, it just takes $var1 and makes it the first value in a new PHP array, and assigns that array to $var2. We talk more about arrays in another video, but basically they’re just a way of holding sets of data together. And doing a type cast like this just makes a set with one item – the variable being cast.

Moving on, if you want to cast your variable as a boolean, you just do this:

$var2 = (bool)$var1;

-or-

$var2 = (boolean)$var1;

When converting an int to a boolean, in this case you’ll get true. In fact any int other than 0 will convert to true. Besides the int 0, other values that will convert to false are an empty string, an empty array, and a null. Everything else converts to true.

As far as converting things to ints, all you need to do is:

$var2 = (int)$var1;

or

$var2 = (integer)$var1;

PHP knows that int and integer mean the same thing. If you convert a boolean to an int, a value of true becomes 1, and a value of false becomes 0.

$var1 = true;
$var2 = (int)$var1; //$var2 is now 1

If you convert an array to an int, if the array is empty you get a 0, and otherwise you get a 1;

$var1 = array(56, 80);
$var2 = (int)$var1; //$var2 is now a 1

If you convert a string to an int, then if that string begins with a number, the int you convert to will have that number as its value

$var1 = ‘340,339,234’;
$var2 = (int)$var1; //$var2 is now 340

Notice that even though the number is written out as a string with commas representing the thousands and millions places, because those commas are non-numeric, the integer conversion stops at the first comma and only gives back the first 3 digits before the comma. And if the string doesn’t start with a numeral, even if there are numbers later in it, the converted value is a 0. One exception, by the way, is if the string starts with spaces followed by numbers. If that happens, the spaces get ignored and the numbers after them are used to create the integer.

Converting to a string from a boolean is simple. If your boolean is true, you get the string ‘true’. If your boolean is false, you get the string ‘false’.

Converting an array to a string is even simpler. No matter what the value of your array, whether it’s empty or not, the string representation is always the capitalized word ‘Array’.

February 06 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on PHP Variable Types

PHP Variables

PHP variables can hold any type of data the language supports, and they don’t need to be declared before they are used. In programmer terms, we refer to PHP as a loosely-typed language.

All PHP variables begin with a $ and are followed by a sequence of characters. Valid characters are letters, numbers, and the underscore. However, a variable may not begin with a number. If it does, the PHP engine will see it and throw a parse error and your script won’t be able to run.

When your script runs, it gets read by the interpreter from top to bottom. A variable won’t have a value until it gets assigned one. Further down in the script you can access that variable’s value.

Assigning a literal value to a variable is pretty simple. You just write something like:

$var1 = ‘I am a variable’;

By the way, when I talk about literals, I mean like a literal 5 or a string inside of quotes. Literals, by themselves, are valid expressions in PHP. They don’t do anything, but they don’t break anything either.

{write ‘next line’; underneath first line}

In this case $var1 now holds the string of characters ‘I am a variable’ that were set inside the single-quotes.

Notice that the statement ends in a semi-colon. All PHP statements end in semi-colons. If you forget them, you’ll trigger a parser error and your script won’t run.

If you’re using an editor like I do, it’ll typically point out any mistakes like that for you. Different editors mark errors differently, but mine just displays a red wavy underline.

{show editor and point out mistake}

In the case of a missing semi-colon, notice the error is actually marked on the next line. This is because PHP ignores white-space. You could stick your semi-colon as far apart from your statements as you like really. So in this case, the error is I’ve started my next statement before closing the previous one.

Now, if you’re familiar with a more strictly-typed language, PHP’s looseness can look pretty strange. There is nothing wrong with suddenly changing my variable from one type to another.

$var1 = 5.8; //now it’s a float!
$var1 = true; //now it’s a boolean
$var1 = 1; //now it’s an int

And if I suddenly start using an undeclared variable as, for example, an array, PHP just creates an empty array in that variable’s place and then starts acting on it however I’ve told it to.

$var2[0] = 5; //$var2 is suddenly an array with key ‘0’ set to the value ‘5’

Likewise, if I use the increment operator – two plus signs together, PHP assumes I want an int, sets its value to 0, and then increments it like I asked, so I end up with the int ‘1’.

$var3++; //when I check it next time, $var3 will equal 1

PHP is so loosely typed that you can even mix operand types in some cases. If you’re unfamiliar with the terminology, an operand is an expression on one side of an operator, like a plus sign. So for instance, you can concatenate a number with a string. It just treats the number as though it were the string representation of it, and adds it to the string:

$var1 = 1;
$var2 = ‘Hello There! ‘ . $var1;  //$var2 is now ‘Hello There! 1’;

It works the other way too. If you try to perform a math operation on a string, it just converts the string to a numeric representation and then proceeds with whatever math you wanted to do. The way it does this is by only looking at the beginning of a string. If there’s a number there, that’s the number it uses it as. If not, then it just gets used as a 0.

$var1 = ‘Hello’;
$var2 = 3+$var1; //$var2 is now 3
$var3 = ’12 cans of rice’;
$var4 = 5*$var3; //$var3 is treated as 12, so $var4 is now 5*12, which is 60

Mixing operand types only works in some cases. It depends on the types and it depends on the operator. We’ll look more at both variable types and operators in later videos.

It might look strange if you’ve ever coded with strict types, but it’s actually pretty freeing once you’re used to it. Of course, it makes it that much easier to make a mistake. If you have a variable called ‘$myWritable’, and you use it all throughout your script, but then in one place you accidentally misspell it as ‘$myWriteable’, PHP will simply assume you want a new variable, default its value to null, and then use it for whatever you tell it to. Unless you use it in a way that will specifically crash if the value is null, you won’t get an error. You’ll simply not get the results you expect, and it can be a pain to have to track it down and fix it.

February 05 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on PHP Variables

Basic Language Functions

PHP includes a number of convenient built-in functions. These built-in functions are written in C, and are all faster than what you could accomplish with a custom function written in PHP.

The set of functions I want to introduce you to in this video all deal with your variables and what they are.

The first function is called ‘isset’. ‘isset’ will return true if you call it on a variable that has been assigned to a non-null value. Unlike most other PHP functions, isset is actually a language construct. For most purposes, there isn’t much distinction between it and the other built-in functions. However, it’s worth pointing out that you must invoke it on a variable, even one you haven’t yet declared. If you try invoking it on a string or an int or the return value of another function, your script will fail to execute, and even with error reporting enabled, you won’t see an error notice.

{show isset being called with a literal}

Generally mentioned in the same breath as ‘isset’ is the function ‘unset’. unset is also a language construct, and also cannot be called on anything other than a variable. All it does is clear a variable’s contents and remove it from memory. If you try accessing that variable again later, it’s value will report as null.

The last language construct in this set is the function ’empty’. In some sense you can think of it like the counterpart to isset. Again, it can only be called on a variable, but instead of telling you whether a variable is set, it tells you whether that variable evaluates to false. So, if you set a variable to either null, the empty string, the boolean false, an empty array, or the number 0 it will return ‘true’, because when PHP converts any of those to booleans they all evaluate to false. I know, the logic sounds a little backwards when I explain it that way, but that’s how it works. If you test a variable with any value that evaluates to true, ’empty’ returns false.

The next set of methods can tell you much more about what a variable actually is, and these are not language constructs, by the way. Whereas language constructs are the lowest-level elements of the PHP language, the rest of these functions (like most functions PHP provides) are built up from a combination of C code and the language constructs. As far as your everyday coding goes, if you use Zend Studio, as I do, it just means that they don’t get colored blue automatically when you type them. You could also invoke them on literal strings or ints, the return values of other functions or whatever, and not just actual variables, if you were so inclined.

Now, I’m going to go through these kind of fast, but one of the nice things about these functions is I can just introduce them by name and it’s obvious what they do. So, first we have is_array to test whether a variable is an array. is_object tests whether something is an object. is_resource checks for resources. We talk more about objects in a later chapter. You can use is_scalar to test for something that’s neither an array, a resource, nor an object. is_numeric tests for numbers, whether they’re ints or floats. If you just want to test for a float, you can use is_float or is_double (they’re exactly the same functions). If you just want to test for ints, you can use is_int, is_integer, or is_long (all 3 are exactly the same function). is_string tests for strings. is_boolean tests for booleans. There’s even a function to test for nulls called ‘is_null’. Functionally, is_null is the exact opposite of isset, except that it won’t crash your script to call it on a literal or on the return value of another function.

At this point you’ve probably noticed a pattern. If you just start searching for functions starting with the prefix ‘is_’ you’re going to find a whole lot more just like the ones I’ve mentioned.

{bring up PHPfr showing all functions with the ‘is_’ prefix}

Every different variable type has an ‘is’ function associated with it. And there are very useful ‘is’ functions to test for things like whether or not a particular constant has been defined, whether a particular directory is writable, whether an object is an instance of a particular class or sub-class, whether the filepath you’re working with represents a file that’s been uploaded from a form. The list isn’t exactly endless, but it’s pretty darn long. All of these functions perform some sort of test on your variable and return true or false depending on the test and the variable. The ones I’ve mentioned are probably the ones you’ll use the most, but they all have their place once in a while.

If you don’t want to run a true-false test for the type of a variable, but just want the variable directly, use ‘gettype’. It has 8 possible return values:

{bring up PHPfr page for ‘gettype’}

array
int
double – we usually call these floats, but it’s returned as ‘double’ for historical reasons
string
resource
object
boolean
null

February 04 2010 | Basics and Built-in PHP functions and PHP tutorial scripts and Schmategories | Comments Off on Basic Language Functions

An introduction to magic methods

PHP 5 introduced a number of powerful upgrades to assist object-oriented programmers. The one we’re going to look at next is called magic methods. And as you can guess from the name, they’re pretty amazing.

First off, let me explain what makes a method “magic”. A magic method adds some additional functionality to your objects, and the way it works is by providing an interface through which the PHP engine can interact with them. {show website} As of this video, there are 14 magic methods, and I definitely want to encourage you to at least be familiar with all of them. The php manual at php.net has an excellent treatment of them, but right now, I’m just going to show you the 4 methods that I think you’ll probably get the most use out of.

Now, just so you recognize them, all magic methods identify themselves by having two underscore characters in front of their names. As a commonsense guide, you shouldn’t create them unless you specifically want the magic functionality. Some of these methods can be accessed directly like ordinary methods, while others can’t – if you want to know which are which, the best way to find out is to test. And since any magic methods added in the future will also begin with two underscore characters, it is strongly discouraged for you to begin any of your regular method names that way.

So, the first method I want to show you is called __construct. Like most magic methods, it should be obvious what it does just from its name. In this case, the __construct method gets called as soon as you create a new instance of your class. Whichever arguments you send in your call to the ‘new’ statement also get sent to the __construct method.

This function is called a constructor, and unlike the other magic methods, this functionality isn’t new to PHP 5. However, back before PHP 5, constructors were simply methods defined with the same names as the classes they were defined in. And, to preserve backwards-compatibility, this convention, while deprecated, does still work. If you have both a __construct method, and an old-style constructor, the __construct method will be the only one called during a ‘new’ statement.

The next 3 methods provide brand new functionality that PHP didn’t have before. The common theme here is that they automatically get invoked when your scripts attempt to access properties or methods on your objects that either aren’t defined, or aren’t declared as public.

The first method of these methods is called __get.

When you try to retrieve the value of a property that isn’t public, or doesn’t exist, before triggering a notice, PHP checks to see whether your object has one of these __get methods. If it does, then PHP will invoke it and pass in the name of the property requested by your script as the only argument. Here’s a simple example of a __get method:

{show example code}

Now, in this case, my class doesn’t define any public properties, but it does define a private property called _options, which is an array. So, whenever a property is requested, it checks to see if the _options array has a value set on the same key as the name of the property the script was trying to access. And if there isn’t one set, it just returns false.

The counterpart to the __get method is the __set method, and from the name, you can probably guess that it gets invoked when a script tries to set a property that isn’t public. This method takes 2 arguments. The first is the name of the property to be set, and the second is the value that the script tried to assign that property.

{show example}

In this case, the __set method on my class is extremely simple. It just sets a value on the _options array based on the key and value passed to it.

The last method I’m going to show you is __call. And this one gets invoked whenever a script attempts to access a method that hasn’t been defined or at least hasn’t been declared as public. It accepts 2 arguments – the name of the method requested, and the arguments that the calling script tried to pass to it. The second argument, in this case, is an array.

Now, my class doesn’t define any non-magic methods, but it does have a private property called _helper. _helper is an instance of the Helper class, and that class does define public methods. Well, it defines one anyway.

{show code sample}

So, what I decided to do in my __call method

{show code sample}

is to check to see whether or not the _helper object has a method with the same name as the one that the calling script tried to access, and if it does, it will call that method with the same arguments that were used when the script tried to access it.

Now, if you know your design patterns, you’ll recognize that this a handy technique in case you want to use the Bridge pattern. And actually, I also want to call your attention to the nifty PHP function here ‘call_user_func_array’. In these videos, I make no effort to try and cover all the useful built-in functions PHP comes loaded with (there’s just too many), but this is a pretty cool one. When I call it this way like you see here, it actually acts exactly as though I had called this method here with these arguments, even though they’re variables. That means there’s no performance penalty the way you’d expect if you tried to mimic this exact same functionality using an eval statement. So if you aren’t already familiar with it, I recommend learning about this function and all the different ways it can be invoked. Look it up in the PHP manual when you have a chance.

Back to the topic at hand though, now that I’ve introduced you to these four methods, let’s take a look at some sample code to see them in action.

{show sample code}

Here you see I’m going to create a new instance of my Magical class. Then, I’m going to set a property named ‘two’ with an array, but of course, since my class doesn’t define a property called ‘two’ it’ll have to invoke the ‘__set’ magic method. Next I’m going to retrieve that property, and use var_export to display it on the screen, which means PHP will also have to invoke my __get magic method.

{switch to output}

And there, sure enough, you see the message “I was constructed” coming out of the constructor, and there below it is the exported array. So we know the first 3 methods worked.

{switch to code}

Lastly, I’m going to place a call to a method named ‘doSomething’ which doesn’t actually have a definition in the Magical class, but does have a definition on the Helper class, and you’ll see the output from that.

{switch to output}

And that right there is the correct output based on the arguments I passed.

Now, the line ‘Good-bye’ at the end of the script probably looks a little strange. But it’s there for a good reason. The class ‘Magical’ actually defines all 14 magic methods, and just like there’s one that gets invoked when an object is created, there’s one that gets invoked when an object gets destroyed. In this case, all it does is print out that message ‘Good-bye’. If you’re interested, I invite you to check out the Magical class in the files included with this lesson. There you’ll see at least 10 other methods I didn’t talk about, and if you want to learn even more, just search the PHP manual for “magic methods”.

{show website}

I should mention before I wrap up, that __call has a static analog called __callStatic. It gets invoked when you try to call a static method on a class that hasn’t been declared, or else isn’t declared public. And also, at the time I’m recording this, a change request has been approved by the PHP engineers to incorporate a __getStatic and __setStatic pair of methods as well. Depending on how old these videos are, those methods might be available to you today. I’d use them in some of my scripts right now if I could. As it is, there’s no way to avoid a fatal error if you try to access an undeclared static property.

January 21 2010 | PHP tutorial scripts | Comments Off on An introduction to magic methods

What's new in PHP 5.3 – Namespaces

PHP 5.3 included a couple of significant new features that are worth giving their own space to cover. These are “namespaces” and “late static bindings”. I’ll discuss late static bindings in the chapter on objects and classes, but in this video we’ll look at namespaces.

Something you will see fairly often in larger PHP applications is classes with names like: Doc_Event_Model_BuildHelper
This sort of name is common, and provides a couple handy features. For one, if it follows the typical convention, you know that within whatever directory classes are kept, there is probably a folder called ‘doc’ with a folder called ‘event’ with a folder called ‘model’ with a file called ‘BuildHelper.php’. And assuming it’s PHP 5 or later, then there is most likely an __autoload function that tells PHP which path to check when trying to load this class. The other useful trait is that it avoids naming collisions. In PHP, no 2 classes can have the same name (and neither can constants or functions).

The downside to this convention is that class names can get very long, and there isn’t a similar convention for constants or functions, which similarly can’t have more than one instance of the same name. As a result, large programs often won’t define functions or constants except as static methods or constants on these long-named classes. Namespaces give you an alternate way of relating the various parts of your code, and prevents naming collisions with unrelated components.

The most basic way to think about namespaces is to liken them to your file manager’s directory structure. If all of your files were in the same folder, then no 2 files could have the same name, and as you added files over time, the file names would need to get pretty long to avoid overwriting existing files. So instead, we can use directories to organize our files into smaller related groups. And when you need to refer to a file, you can use a relative path or an absolute path.

With namespaces, like directories, we arrange our code into related parts. When we refer to namespaced code, we also use absolute or relative names. To use the proper terminology, we refer to these names as either as ‘qualified’, ‘unqualified’, or ‘fully-qualified’.

For instance, in the namespace ‘Foo’, a call like ‘$a = new Bar()’ would actually attempt to create a new instance of ‘Foo\Bar’, meaning some class called “Bar” within the namespace “Foo”. And in this case, we would refer to “Bar” as an unqualified name, since it has no namespace qualifier preceding it.

On the other hand, a fully-qualified name is like an absolute path to a file in your directory. The system knows it’s fully-qualified because it begins with a “\” character. So, using the example above, we might write “$a = new \Foo\Bar()”. In both examples, PHP would interpret this as a call to create a new instance of the class “Bar” residing in the namespace “Foo”.

Another way to create a fully-qualified name is to use the special “namespace” keyword. In this context, it acts much like the “self” keyword for a class. We could change our code to “$a = new namespace\Bar()” and it would again do the same thing. The usefulness here is that you can write code that is totally agnostic about the actual namespace it resides in, so long as it does actually contain some class by the name of “Bar”.

A “qualified name” is analogous to a relative path to a file within a sub-folder. You can have sub-namespaces the same as you can have sub-folders. So, back to our previous example, suppose there was a sub-namespace within Foo called “AnotherFoo,” which also had a class called “Bar”. If we wanted to specify that we were using that class instead, we could write “$a = new AnotherFoo\Bar()”. Notice there’s no forward slash at the beginning of the class name. So, what we actually get, in terms of a fully-qualified name, would be \Foo\AnotherFoo\Bar.

PHP will convert unqualified and qualified names into fully-qualified names at compile time.

Now that we’ve explored terminology, let’s look at how we actually define our code within a namespace.

When you declare a namespace within a file, it must come at the very start of the file. The only exception PHP allows is a declare statement to identify the type of encoding for the file. Consider the following code:
<html>
<?php
namespace Joe {

}

this code throws a fatal error because of the line above the php tag.

However if this is how your file begins:
<?php
namespace Joe {

}

Then you’re fine.

When you declare a namespace, any files you include within that namespace will also be a part of it. If the file ‘mover.php’ contains the class ‘Mover’, then in the following code:

namespace Joe {
include(“mover.php”);

}

the fully-qualified name for the class Mover will actually be \Joe\Mover.

In the same way, if you include a file that also defines a namespace from within a namespace, then that included namespace is going to be a sub-namespace.

For instance, if the following lines begin a file included within the namespace declaration ‘A’

namespace B {

function do_something() {

}

}

then the fully-qualified call to that function would be \A\B\do_something().

To be really useful though, it would be nice to be able to avoid writing a number of separate ‘include’ calls, and simply use the power of PHP 5’s ‘__autoload’ capability. __autoload is a special global function that PHP calls when an unrecognized class is referred to, instead of simply throwing an error (a la PHP 4). This function attempts to include a file based on the name of the class, in hopes that the referenced class will be found there.

Creating a custom __autoload function will be discussed in a separate video, but one of the most wonderful things about PHP 5.3 is that most of us won’t need to write one – the default __autoload function included with SPL already understands namespaces.

To enable, just call ‘spl_autoload_register()’ without paramters. If you want to specify a certain directory containing your classes, use ‘set_include_path’ to ensure that the autoload function checks there. And you can make sure that php uses a specific extension, such as ‘.class.php’ by calling ‘spl_autoload_extensions()’. Check out this example:

set_include_path(get_include_path() . ‘/classes’);
spl_autoload_extensions(‘.class.php’);
spl_autoload_register();

Now, whenever the code tries calling a class that hasn’t been included yet, say ‘\Useful\Class\Test’, the code will look inside the folder ‘classes/Useful/Class’ for a file called ‘Test.class.php’. And if it finds it, and the file contains a definition for the class ‘Test’ within the namespace ‘\Useful\Class’, then the class will be used seamlessly, and no explicit include file will be necessary.

Now it’s true that you can write your own __autoload function to do the same exact thing, but the spl_autoload function, since it’s actually written in C and not PHP, is going to be slightly faster. My advice is, whenever possible, try to create your directory structure in such a way as to make use of this handy default behavior.

December 06 2009 | PHP tutorial scripts | Comments Off on What's new in PHP 5.3 – Namespaces

What was introduced in PHP 5

PHP 5 introduced a number of revolutionary features to the language that made it a much more elegant solution to many of the common programming challenges developers face. Object support went from something of a glorified after-thought to a truly compelling, modern approach. Several useful libraries and interfaces were added, and exception handling was finally given the attention many developers had longed for. Each of these are covered in their own chapters, but there were just a few other add-ons that, while too important not to cover, didn’t easily fit into more focused chapters.

Briefly, we’re going to look at three of these new features: type-hinting, objects being passed by reference, and indirect referencing.

Type hinting allows you to more precisely specify the types of arguments that should be passed into your function. In the definition, you can do something like:

function myFunction(MyClass $object) {
//do something with $object
}

This sets up a guarantee that when the function is run, $object will either be an instance of “MyClass”, an instance of a child class of MyClass type, or an instance of a class that implements an interface called MyClass. And this might be really important. Having it specified this way in the function definition will also ensure that anyone working on your code later will know that. In addition to class and interface names, you can also type-hint for arrays. The ‘null’ value is always allowed as a default:

function myFunction(MyClass $object = null) {
//if no argument is passed, or if a null is passed explicitly, this function will work
}

But you cannot have something like this:

function myFunction(MyClass $object = new MyClass()) {
//this code will not parse
}

Oddly enough though, you CAN do this:

function myFunction(array $array = array()) {
//this code is perfectly legit
}

And you cannot type-hint for scalars, like ‘int’, ‘float’, or ‘string’:

function myFunction(int $int) {
//won’t work in PHP 5 – maybe PHP 6 will allow?
}

However, there is one warning to bear in mind with this approach. If the argument is NOT an instance of MyClass (or a child, or an implementer) your script will trigger a catchable fatal error, not an exception. In order to deal with this type of fatal error, you need to create a global-scope function and use it as the argument in a call to ‘set_error_handler()’ to replace PHP’s default handler. We’ll take a closer look at creating custom error handlers in another video, but here’s some code we could use in this situation:

{@todo – write and test example error-handler code}

However, if you’d rather not deal with custom error handlers, there are other ways to ensure that your function is getting the variable type you expect, and still make it clear to those who follow what is expected. There is a special docblock comment tagline “@param”. If you use a development environment such as Zend Studio, or run phpDocumentor on your code, the argument requirement will be listed along with the function documentation. And if you want to halt execution when the wrong argument type is passed, you can test the type explicitly within your function and throw an exception that can be caught and handled properly. Here’s what that looks like in practice:

/**
* this function does something useful
* @param MyClass $object
*/
function myFunction($object) {
if(! $object instanceof MyClass) {
throw new InvalidArgumentException(‘$object must be an instance of MyClass’);
}
//do something
}

We’ll look more at docblock comments as well as phpDocumentor in another video. But suffice to say this approach will work in many of the situations when you might consider using type-hinting, and it can be made to work with multiple types and scalars. The disadvantage, of course, is somewhat longer code, and needing to ensure that your function is called within the scope of a matching try-catch block.

The “instanceof” keyword, by the way, is also new to PHP 5. It’s essentially an analog to the is_a() function that’s been around since PHP 4. Like type-hinting, it tests whether an object is an instance of, a child of, or an implementation of the class or interface name in the right-hand argument.

For a while, the PHP engineers had decided to deprecate “is_a()” in favor of the instanceof keyword, and in PHP 5 before 5.3, it would toss an E_STRICT warning. However, as of PHP 5.3 it is no longer deprecated. Both is_a() and instanceof are now considered equally valid.

Perhaps the most significant change between PHP 4 and 5 is the fact that objects are now passed by reference by default. The reason I say it’s the most significant isn’t because it completely revolutionizes the language – PHP 4 could pass objects by reference by using the ‘&’ in front of variables in a function definition, as in the example shown here:

function myFunction(&$obj) {
//In PHP 4, $obj is a reference to an object, rather than a copy of it
}

The reason it’s so significant is because, while the PHP engineers worked very hard to make sure almost all PHP 4 scripts would work the same under PHP 5, this is one area where they might not. Consider the following code:

class Account {
var $balance = 0;

static function addFunds($account, $amount) {
$account->balance += $amount;
}
}

$account = new Account();
Account::addFunds($account, 20);
echo $account->balance;

In PHP 5, the output will be ’20’, but in PHP 4, no change actually takes place to the $account object, so the output is ‘0’. Under PHP 4, the function gets a copy of the $account variable, rather than a reference to the original variable as it does in PHP 5. And in this example, obviously it’s the PHP 5 behavior that would be intended. But that’s not always the case.

Imagine that a PHP 4 script were written that takes an object and performs some action on it with the expectation that it NOT change the original object. Trying to run that same script in PHP 5 could result in very unexpected behavior. And indeed, if your old scripts break when running under PHP 5, there’s a good chance that this new behavior is behind it.

Now, because there are some situations where you want the ability to work on a copy of an object rather than the object itself, PHP 5 provides an easy mechanism for doing that.

$object = new MyClass(5, 5);
$copyOfObject = clone $object;

In this case, any properties set in $object will be set identically in $copyOfObject, so making changes to $copyOfObject won’t affect $object. In another video we look at how you can have more fine-grained control over exactly how an object is copied by defining the __clone() method in your class, but for most cases, the default behavior of ‘clone’ is sufficient.

The final addition to PHP 5 we’re going to look at is called “indirect referencing”. And it’s a great way to take many lines of code and turn them into just a few. Consider this example from a typical PHP 4 script:

$var1 = $object->var1;
$var2 = $var1->var2;

var1 is actually an object itself that also happens to be a property on $object, and var2 is a property of var1. In PHP 5 we can shorten this to just:

$var2 = $object->var1->var2;

In PHP 5, there is no need to actually declare temporary variables in these types of situations. The code above will simply get the first variable and then use it to get the subsequent variable. It works for functions and methods as well:

$var2 = $object->method1()->var2;
$var2 = myFunction()->var2;
$var8 = $object->var1->method2()->var3->method4()->method5()->var6->var7->var8;
//so long as an object is returned with each ‘get’ or method call (aside from the last), all these examples are valid!

Indirect referencing leads to a handy programming technique called “chaining”. The last example shows how it can drastically shorten code versus PHP 4.

There were a number of other important changes introduced in PHP 5, and several of those will be examined in the section on Object Oriented Programming, but this concludes the ones I wanted to look at here.

October 14 2009 | introduction and PHP tutorial scripts | Comments Off on What was introduced in PHP 5

Exception-handling with try-catch blocks

PHP 5 introduced something that programmers in other languages had come to rely on for exception handling. It’s called the try-catch block. In most languages that use the try-catch block, any time a run-time error occurs, it can be trapped inside a catch statement and dealt with in some manner appropriate for that particular situation. This is not the case in PHP 5.

Actual errors that the PHP engine generates aren’t considered exceptions the way they’re defined here, which is why it’s important to understand the difference between errors and exceptions. But if you want your code to generate and deal with procedural anomalies of any sort, or if you just want to halt execution without using a return statement, then exceptions are a fantastic tool to learn. PHP does provide a means for actual error-handling, but that topic is covered in another video.

So anyway, with the try-catch blocks, here is the basic syntax:

try {
//run some code
} catch(Exception $e) {
//do something
}

Basically, the code inside the try block runs, and if it causes an exception to be thrown, then execution of that block stops immediately, and the engine jumps into the catch block to begin execution. Exceptions are only thrown by actual PHP code. So your scripts and libraries may throw an exception, but if there’s an error within the PHP engine itself, the catch block won’t be triggered.

Take a look at the following example:

if($db->connect() === false) {
throw new Exception(‘could not connect to database’);
}

If this particular code is executed from within a try block, and the connect() method returns false, then the corresponding catch block will be called. It’s important to note that uncaught exceptions result in fatal errors, so don’t throw them unless you’re sure there’s a catch clause to deal with it. Alternately, if you want a last-resort catch clause, you can set a global exception handler. However, since the syntax for that is so similar to setting a custom error handler, I talk about that in the same video where I discuss setting custom error handlers.

The throw statement can act similar to a return in that it halts execution of a function (or at least, it will if it isn’t thrown within a try block), but instead of just returning to the point where that function was actually called, it continues up the stack until it finds a corresponding catch block.

Now, what I mean by corresponding catch block is one that matches the type of exception being thrown. The example above uses the basic class “Exception”, but that’s not the only option. PHP 5 provides several more specific Exception classes you can use, and it’s a simple matter to create your own. The catch block makes it clear what type of exception it can receive. Since all exceptions are based on the “Exception” class, a catch block like this:

catch(Exception $e)

will catch any type of exception thrown in its corresponding try block.

But supposing I wanted to handle different types of exceptions differently. A single try block can lead to multiple catch blocks:

try {
throw new UnexpectedValueException(‘unexpected!’);
} catch(InvalidArgumentException $i) {
echo ‘InvalidArgumentException: ‘ . $i->getMessage();
} catch(UnexpectedValueException $u) {
echo ‘UnexpectedValueException: ‘ . $u->getMessage();
} catch(Exception $e) {
echo ‘Exception: ‘ . $e->getMessage();
}

The code shown here will display “UnexpectedValueException: unexpected!” because the second catch block is the one that corresponds to the type of error thrown. However, since all exceptions are of the type “Exception” changing the code to the form shown below will change the output:

try {
throw new UnexpectedValueException(‘unexpected!’);
} catch(InvalidArgumentException $i) {
echo ‘InvalidArgumentException: ‘ . $i->getMessage();
} catch(Exception $e) {
echo ‘Exception: ‘ . $e->getMessage();
} catch(UnexpectedValueException $u) {
echo ‘UnexpectedValueException: ‘ . $u->getMessage();
}

This code will display “Exception: unexpected!”. That’s because PHP will go through each catch block in order until it finds one that matches, and then it will stop. Even though “catch(UnexpectedValueException $u)” is the BEST match, “catch(Exception $e)” is the FIRST match.

Alternately, the example below will simply cause a fatal error unless it’s called within the scope of a matching try-catch block higher up in the stack:

try {
throw new UnexpectedValueException(‘unexpected!’);
} catch(InvalidArgumentException $i) {
echo ‘InvalidArgumentException: ‘ . $i->getMessage();
}

Since the type of exception thrown doesn’t match any catch block.

In the above examples I used, InvalidArgumentException and UnexpectedValueException are actually built into PHP 5, along with several others. But inventing your own exception class is as simple as:

class MyNewException extends Exception { //no class code needed!
}

Include that class definition somewhere in your project space, and you can throw and catch MyNewException wherever you want. The name just helps differentiate exception types. This technique is useful for detecting when something unexpected has happened and dealing with it.

When catching an exception, the argument after the type of exception is a reference to the actual exception itself. In the case of:

try {
//do something
catch(Exception $e) {
//do something
}

“$e” is the specific object of the Exception class that was thrown and caught.

The exception class itself provides several methods you should know about. You can see more examples by searching php.net.

$e->getMessage();

Exceptions can be thrown with no arguments, but for debugging purposes, it’s usually helpful to include at least the first argument, a string, telling why the exception was thrown. For instance, if the script does this:
try {
throw new Exception(‘Go directly to the catch block’);
} catch(Exception $e) {
echo $e->getMessage();
}
the script will print “Go directly to the catch block”. Obviously, this isn’t a particularly helpful message, but you get the idea.

The second argument for an exception, if provided, is a code. Again, you can choose whatever you want, and calling “getCode()” will just return whatever you provided. Some programmers prefer to use numbers to classify their exceptions, since they can be a little less ambiguous than strings. And obviously, there’s no reason you can’t use both messages and codes in your exception. Here’s the syntax:

$e->getCode();

And an example:

define(‘EXAMPLE_EXCEPTION’, 55);
try {
throw new Exception(‘an example exception occurred’, EXAMPLE_EXCEPTION);
} catch(Exception $e) {
echo $e->getCode();
}

And this script would print “55”.

The final argument for creating an exception is another exception. The idea is that if an exception is caught in one catch block, and then a new one is thrown again, the newer exception can contain a reference to the old one. This isn’t something you see very often, but it’s easy enough to understand. Here’s another simple example:

try {
try {
throw new Exception(‘This is the way it is’);
} catch(Exception $e1) {
throw new Exception(‘Here is what I think’, null, $e1);
}
} catch(Exception $e2) {
$e1 = $e2->getPrevious();
echo $e2->getMessage() . ”
“;
echo $e1->getMessage();
}
And this code will print “Here is what I think” followed by “This is the way it is” on the line below.

In addition, the exception can return information about the stack at the time it was thrown. There are a couple different functions for this depending on whether you want the back trace as a string or an array, or whether you just need the specific line or file where the exception took place. Here they are very briefly:

$e->getTraceAsString();

returns the entire trace as a string

$e->getTrace();

returns an array where each line in the stack is a separate element

$e->getFile();

returns the path to the file where the exception was thrown

$e->getLine();

returns the line number where the exception was thrown

October 13 2009 | introduction and PHP tutorial scripts | Comments Off on Exception-handling with try-catch blocks

Introduction

PHP has become one of the most prominent web development languages in production today. Part of this is because it is so easy for someone to dabble with it and achieve immediate results. It takes very little expertise to incorporate PHP into an otherwise straightforward html page, and that makes it popular with many designers.

The fact that those first few steps are so easy helped the language achieve some of its initial adoption, but that’s only part of the reason it’s become so widespread. While a web designer might appreciate a simple way to rotate a banner ad, or change some style based on the date or time, a skilled web developer can actually power the entire website, from serving up content, to managing access permissions, and interacting with data from around the internet. PHP is a powerful language, and while that power can be dangerous, it can be incredibly freeing to a developer.

Most large websites, including heavyweights such as Google, Yahoo, Amazon, and Paypal, provide developers tools for interacting with them through their own PHP scripts.

Many websites – large and small – use PHP to power their content management system, or CMS.

And there are a number of open source projects, written in PHP, that harness the collective skill of thousands to create truly great software. My personal website, powered by WordPress, is one example of such an effort. Others you might be familiar with include Joomla, Drupal, and phpBB.

The goal of this training course will be to take you from a basic understanding of PHP to what can be called an advanced level. At this point, you should already be comfortable writing functions and classes, using the basic language constructs like loops and conditional statements, connecting your scripts with a database and interacting with the server’s filesystem. You should know some of the more common functions provided by PHP itself, and for the most part, you should be able to look at another developer’s PHP code and figure out what it does.

At an advanced level however, you’ll need to be aware of the various tools and libraries available to you as a developer and how to incorporate them. You’ll want to gain a deep understanding of how object-oriented programming should work in PHP, so you can put it to the best possible use in your scripts. And perhaps most important, you’ll need to learn how to secure your websites and web applications against all the ways someone might try to exploit them.

PHP has earned its place of prominence because of its ease of use, power, and scalability. It is well supported, and well documented, and is unlikely to lose its popularity within the foreseeable future.

October 13 2009 | introduction and PHP tutorial scripts | Comments Off on Introduction

« Prev