Archive for the 'PHP tutorial scripts' Category

Commenting

So far we’ve only looked at how to write PHP code. But just as important as your code can be the comments you write to explain what your code does.

PHP supports 3 different ways of writing comments. The first 2 are borrowed from C. There’s the double forward-slash format:

//this is a comment

and the multi-line comment:

/*
This is a comment that can include many lines
*/

And lastly there’s the shell-style comment with the # sign:

#this is another comment for just one line

The way the single line comment works is that everything following the start of your comment until the next new-line will be commented out and ignored by the interpreter, but with one rather important exception: PHP ending tags.

So, for instance, the following code will break:

//  echo ‘<?xml ?>’;

And it doesn’t matter whether that’s a pair of forward slashes or a pound sign. Personally, I always use the forward slashes since there’s no functional difference between them, and it’s what I’m used to.

But anyway, what’ll happen is that the ?> will be seen by the interpreter as an end of the PHP block. Anything after that will just get printed directly to the page. Without the comment, PHP would have seen that as part of a quoted string, and known not to treat it like an ending tag. But once you have the comment there, it won’t recognize the quotes around it. It’ll just be treated like a closing PHP tag.

In this case, the only solution, if you really need that line commented out, would be to use the multi-line style comment. However, you have the freedom with that comment type to comment just a section of a single line.

Basically, the way multi-line comments work is they tell the interpeter to ignore anything between a /* and a */. Once the interpreter enters a comment block of that type, the only thing it looks for is an ending mark for that comment. And if it finds it on the same line or a thousand lines down the page, it makes no difference as far as the interpreter is concerned.

So, rewriting that comment:

/* echo ‘<?xml ?>’; */

And that comment will work just fine.

It’s worth noting that the multi-line comment ignores PHP ending tags as well. So, something like this:

<?php /* ?>

<p>Here is some HTML</p>

<?php */ ?>

would be a way of commenting out a section of HTML so that it didn’t get sent to the page. Just remove the beginning and ending tags for the comments and the HTML fragment will re-appear.

Now, the pit-fall with this type of comment usually happens when you try to nest them by mistake. Suppose you need to comment out a large block of code, but somewhere in that code there’s already a multi-line comment block, for instance like this:

/*

… lots of PHP code

/*
The following function does something wonderful
*/
function doSomething() {
//… do something wonderful
}
… more PHP code

*/

In this case, the PHP interpreter would see the first comment-ending tag, and treat everything after it as regular PHP. But then it would hit the intended comment-ending tag, and throw a fatal parsing error, since ‘*/’ isn’t a recognized PHP expression.

So, just be careful when blocking out large sections of code this way. If you use an editing environment like mine, it’ll alert you to this sort of mistake.

Now that we’ve looked at comments, a good programming tip is to use them to explain in plain English what your script is doing at each step of the way, before you actually write your code. This way, so long as your logic makes sense, you can just write your code to do what you intend to do and be fairly confident that your functionality will work as intended. If there’s a mistake to track down, then knowing exactly what the code ought to be doing can be a huge help, rather than trying to make an informed guess based on contextual clues.

Another use for comments is in removing a line or lines of PHP that you don’t want to execute. This can be especially important when you’re debugging, and we’ll look more at that in a later video.

March 09 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Getting data from the user – part I

When it comes to being really useful, PHP’s greatest benefit comes when it can modify the contents of a page based on how a user interacts with it. Key to that ability is getting information from the user to reach your scripts.

There’s a couple different ways to do that. The first way is by passing information through the URL. You do this with a ? in your URL after the end of the filename, like this:

file.php?name=Joe

In your script, you can access that variable with the special super-global array $_GET, like this:

echo ‘Hello ‘ . $_GET[‘name’];

{show output}

However, it’s worth noting that this is actually a security hazard. We talk more about cross-site scripting later, but imagine some malicious hacker linked to your site like this:

<?php
echo ‘<a href=”file.php?name=’ . rawurlencode(“<script type=\”text/javascript\”>setTimeout(\”alert(‘Your PC is infected with a virus. Click here to buy some fake anti-virus software’)\”,2000);</script>”) . ‘”>click here</a>’;
?>
{show result of clicking in firefox}
By the way, for my personal browsing, I typically use Google Chrome. One of the neat things about Chrome is that it notes whenever the URL includes javascript and it won’t run that javascript fragment if it appears in the webpage. It specifically protects me from an attack like this. But firefox, another browser I sometimes use, has no such protection, which is why I’m using it here.

So, to protect your visitors, before you echo out a variable that gets sent directly from the URL, just use one of the special PHP functions like ‘htmlentities’ or ‘strip_tags’ or another similar function:

echo htmlentities($_GET[‘name’]);

{show new output}

So, moving along, to pass more variables, you string them together with the &, as in:

file.php?name=Joe&lastName=Smith

$_GET[‘name’] = htmlentities($_GET[‘name’]);
$_GET[‘lastName’] = htmlentities($_GET[‘lastName’]);
echo “Hello $_GET[name] $_GET[lastName]”;

{show output}

Whether you pass a number or a sequence of characters, doing a gettype proves that these variables are always strings. But that’s ok since anything that can be sent through a URL can be expressed as a string.

Now, this is probably a good time to talk about register_globals. In PHP 5, register_globals is turned off by default, but it’s a directive in PHP that lets variables passed through the URL become variables inside your scripts without needing to go through the $_GET super-global array. It’s turned off in PHP 5 by default in order to get people with PHP 4 scripts to take the time to update their code while still giving them a way to the code work, if they turn it on. In PHP 5.3 register_globals is officially deprecated, and in PHP 6, register_globals is gone.

However, it’s worth mentioning, so I’ve turned it on for the moment. In a later video we examine how to change the ini directives, so I won’t take the time right now to show you how I did it, but here’s the gist of it:

echo “Hello $name $lastName”;

$name and $lastName aren’t defined anywhere in my script. With register_globals, I can add any variable to the global scope just by sticking it into the URL. And since it’s on, here’s the output:

{show output}

So, that was how things were passed from the URL in PHP 4.1 and earlier, back before the superglobal arrays were added to the language. But the PHP engineers decided this made it far too easy to introduce security vulnerabilities. Take this example:

if(reallySecureLoginFunction() === true) {
$authorized = 1;
}

if($authorized == 1) {
include(‘reallySecureContent.php’);
} else {
include(‘userNotAuthorized.php’);
}

Without register_globals, there’s no way for $authorized to be set except in the case that reallySecureLoginFunction returns true. But with register_globals, all the user needs to do if he wants access is add ?authorized=1 to the end of the URL. What the PHP best practices told people to do was make sure that all variables get declared before they’re used – simply adding $authorized = 0 before the call to reallySecureLoginFunction() would have been enough to prevent this security exploit.

But novice programmers, sort of by definition, didn’t know the PHP best practices, and PHP certainly didn’t throw up any kind of error if they didn’t follow them. So, to get rid of the security hole, they turned off register_globals and told people not to turn it on, which is exactly what I’m passing on to you. Don’t turn it on. If you do, and you rely on it being on, you won’t be able to migrate your scripts to PHP 6. And it makes it really easy to accidentally make your scripts insecure.

In addition to simple string variables, I should point out that it is also possible to pass arrays from the URL. The syntax is a little different, but easy to understand, because it uses square brackets just like building a PHP array:

?file.php?names[]=Jim&names[]=Kate&fruits[red]=plum&fruits[yellow]=banana

To access these values in your script, simply treat $_GET like a 2-D array:

echo $_GET[‘names’][0] . ‘ wants a ‘ . $_GET[‘fruits’][‘red’];

Now, you wouldn’t typically expect your users to type these extra parameters into the URL the way I’m doing. Generally, you provide a link, they click it, and these parameters are automatically filled in. To help you build a link with the variables in it, PHP provides a useful function called http_build_query.

http_build_query takes an associative array as the first argument. I you want to use a numeric-indexed array, you can, you just need to provide a prefix so the function can give you valid variable names. That’s your second argument, if you decide to include it. For instance, if you have an array with 3 items that uses numeric indexes, and your prefix is ‘myvar_’ your variables will be myvar_0, myvar_1, and myvar_2. And since they don’t start with numbers, they’re legal variable names. Of course, since register_globals should be off, and you’ll be accessing them inside an array, you can also just leave them as numeric indexes, without the prefix, and access them as keys 0, 1, and 2 inside $_GET.

So, here’s an example of a simple script I’ve created.

{show output}

It gives me a choice of links, and depending on which one I click it shows a different pair of images at the top.

{click links, show changing page}

But these are all using the same PHP script. I’ll show you how it works:

{display script}

So, with nested foreach loops I go through both arrays, and create a combination for each possible image pairing based on the two sets of images, using the keys as the variables I pass through the URL when someone clicks on the link that pairing creates.

Notice the call to http_build_query has one last argument. This is what determines the variable separator. By default, it’s the &, but I’ve picked ‘&amp;’. I did that because to have valid HTML markup, the & needs to be replaced with the special HTML entity, and that’s the code &amp;.

So, that concludes the lesson on passing variables through the URL. In the next video we look at using information collected from forms.

February 14 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Include and require – part II (how to use an included file)

In the previous video we looked at how to specify the location of a file to include both through using an absolute path as well as a path relative to the include path. In this video, we’re going to look more at how and why to include files.

To begin, you might be wondering – what are some situations where you might want to place your data into a separate file? Well, one situation is where you have a configuration file. A config file typically sets up variables that are needed by your script for things like connecting to a database, or connecting to an outside web feed, or setting certain parameters on or off – like whether the site should be in maintenance mode. Depending on how your site is configured, you might even be able to swap out config files and completely change your site from top to bottom. That’s some pretty sweet power when you can do that.

Other possible things to place in external files could be a list of constants you want defined at various points in your script. Since constants all need to be unique, keeping them in one script makes it easier to ensure that you haven’t already named a constant with a certain label. It’s also an easy reference to check when you need to know what constants you’ve already defined.

Pretty much the exact same argument for constants can be made for your custom functions. It can be awfully handy to keep them in their own separate file too.

So, the way this works is as soon as you include a file, any variables set within it become accessible beginning with the line immediately after the include statement. Conversely, any variables already defined by the line of your include statement are available within the file you’re including. In addition, it is entirely acceptable to include a file from within a function, it just won’t have access to variables defined in the global scope. So anyway, here’s a simple example:

{show example scripts}

I’ve written this script to do three simple things. It will define the variable $var1 as ‘hello Mason’. Then it will include the script include.php, and then it will display the value of $var2. Meanwhile over here, my script ‘include.php’ will do just 2 things. It will display the value of $var1, and it will define the variable $var2 as ‘good-bye Mason’.

{show output}

And as you can see we get a quick hello and good-bye message, because $var1 was available in include.php, and $var2 was available in the main script. Now if we flip the main script, and try to access $var2 before we do the include, and then set $var1 after the include:

{show output}

You can see nothing happens, since the variables aren’t yet defined when the scripts try to use them.

Now, the same thing is true of constants. If you try to access them before including the script in which they’re defined, you won’t get their values. What PHP does instead is throw a notice, and depending on your error reporting setting you may or may not know that it threw the notice. And then it just tries to use your constant like a string, as though you had put quotes around its name.

However, this is not the case with functions. When the parser checks over your script, if it sees that your function will definitely be defined, as opposed to defined only if the logic of a particular branch is used, then you can actually call that function higher up in the script than the line where the file that has its definition gets included.

{show example code}

So here the file functions.php gets included further down than my call to doSomething(). But when you look at the output:

{show output}

You see that the function got invoked anyway.

Alright, so last way of using the include statement is with files that don’t contain PHP, or else contain a mix of PHP and other things. When this happens, the contents of your file just get thrown out to the page:

{show example HTML fragment}

{show output}

And you see it showed up. Basically, all an include statement does is add the contents of any file to one long script that the parser generates when it makes its first pass over your code. And then the interpreter actually runs that script. So you don’t need to think about whether you’re adding php or non-php files. They’re all just parts of that one long script. And if there’s no PHP block, the engine just prints them to the page uninterpreted.

An important note about why that last example worked – when you import a file with include or require, PHP does not assume that the included file needs to be interpreted as PHP. If it does, your file needs to include the PHP opening tag. Without it, your file’s contents get output to the page directly with no interpretation.

Another thing to know about include is the fact that PHP supports ‘include_once’ and ‘require_once’. These alternatives can be useful if, for instance, you’re importing a file that defines functions or constants. Including one of these files more than once will trigger a fatal error, since it treats it as though your script is trying to define these multiple times, which isn’t possible in PHP. With include_once and require_once, the PHP engine won’t import the file if it has already been imported previously.

The last thing to know about including and requiring files is that you can use the return statement from within an included file. It works the same as a return statement from within a function. It stops execution of the script, and can optionally return a value. If it does return a value, you can capture that value the same way you would with a regular function. Just assign the value of your include or require statement to a variable in the calling script.

So, let’s look at this in action:

(in calling script)
$returnVal = include ‘./includeMe.php’;
echo $returnVal;

See I’m assigning the return value of this include call to the value $returnVal, and then displaying it.

(in includeMe.php)
<?php
return ‘Hello World!’;
echo ‘Good-bye’;

And in the included script, I’m returning the string ‘Hello World!’ and then displaying ‘Good-bye’.

{show output}

And sure enough, we see ‘Hello World!’ because the calling script was able to use the return value of the included script. But we don’t see the words ‘Good-bye’ because the included script stopped executing after the return statement.

The ability to import files is very useful in PHP, or really any modern programming language. Now that we’ve studied the concept, most of the videos from here on out will involve including or requiring additional files.

February 14 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Include and require – part I (how to include a file)

Up until this point, we’ve only looked at scripts that are contained entirely in a single file. But in PHP you actually have the ability to split your work up into lots of different files. And in fact, this can be a very handy thing to do, as it can allow you to more effectively organize related portions of your code, and also help to prevent a file from becoming too long to understand.

PHP actually supports two different ways of including external files in your script. There is the include statement, and the require statement. There’s an important distinction between these two statements. If you try to include a file with the include statement, and the file doesn’t exist, the script continues executing anyway. On the other hand, if you try to include that same file using the require statement, your script will trigger a fatal error. This can be a handy thing to do when you know that without that file, your script is going to fail anyway, but the require statement’s error is generally going to be a little more obvious and easier to debug than the result you get when it fails at some later point while using include.

Here’s how the statements look:

include(‘includeMe.php’);
require(‘requireMe.php’);

What these statements will do is cause the contents of the specified files to be inserted into your script at the point where the include or require statements are run. Technically, both ‘include’ and ‘require’ are not functions, but actual language constructs, which is why my editor is coloring them blue. Most language constructs have some quirk about them that make it obvious they aren’t actually functions. Include and require are no different. In their case, they’re like echo statements (echo being another language construct), in that they do not need parenthesis around their arguments:

{modify code to demonstrate}

See? The editor isn’t reporting an error.

In this case, you’ll notice my statements are ambiguous about where the files to import are actually located. I’m using what’s  called a relative path. But relative to what? Well, that’s not clear from this context. But obviously my script was written with the assumption that the place PHP looks for these files, called the include path, contains the directory where these files ought to exist.

An include path is a string, and it works like the Windows or Unix environmental variable “PATH”. If you’re not familiar with it, it’s basically one string with either colons separating each directory path if you’re in a Unix environment, or semi-colons separating each if you’re in Windows. And when you use a relative path name, it just searches for the file in each of the include path’s directories, one at a time, until it finds a match, and then it imports that file. If it exists in two locations, only the one that gets checked first will be imported. If I want the second one, I have to use the full path to the file, starting with the root directory.

So now let’s look at the include path on my own PHP install. I’m on a Mac, so its going to use the Unix-style path separator: the colon.

echo get_include_path();

The get_include_path function, since I haven’t modified the path anywhere in my script, is going to get the value set in my php.ini file. We look more at the php.ini settings file in a later chapter. For now, here’s the output from this script:

{show output}

And that tells me which directories I can include from without first altering my include path. Notice the period at the start. This was just the default setting when I installed my XAMPP server. What that does is tell PHP to always check the directory of the file currently being executed first, before looking in other directories. So, if ‘includeMe.php’ and ‘requireMe.php’ exist in the same directory as the script that imports them, I don’t need to make any change to my path in order to import them this way.

Now, suppose we want to get a file that isn’t in this path. Well, if we know the full path to the file, we can either modify the include path if we’re going to be getting several files, or we can use the file’s absolute path if we just need to include from that directory one time.

When you use an absolute path – that is, a path that begins with the root directory, be that a drive letter in Windows or a forward slash in Unix, PHP doesn’t look at the include path setting at all. And because it doesn’t, there is a slight performance benefit from including your files this way. But it’s often the case that we’re not sure of a file’s absolute path ahead of time, or we want the freedom to deploy our code on numerous sites, in which case we can be sure that the absolute paths to our files are going to change. So, a better way to handle this situation is typically to modify the include path once and then use relative paths everywhere else. PHP lets us do that with the set_include_path function.

Since it’s a pretty common task, I’ll show you how to add the current script’s directory to the include path the right way:

set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__);

In this case, I’m not overwriting the existing path, I’m just adding to it. And by the way, the __DIR__ magic constant has only been available since PHP 5.3. On older systems, you would use:

set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__));

The constant ‘PATH_SEPARATOR’ is one of the ones defined for us by PHP, and we can always count on it being the correct value – whether a semi-colon in Windows or a colon in Unix – no matter what system we’re using.

Before I move on though, one last thing I want to point out. Suppose that includeMe.php and requireMe.php really do exist in the same directory as the file that imports them. If that’s the case, then this:

include(‘./includeMe.php’);
require(‘./requireMe.php’);

is considered an absolute path, and so it’s going to be a little bit faster than using the include path, even if it also begins with a period.

That’s all for this video on the include path. In the next video, we’re going to look at what happens when you actually start including files.

February 13 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Variable Scopes and References

We already introduced variable scope while looking at how variables behave in functions, but there’s much more to learn about it. In the video on functions, I hinted that there are ways to access and modify variables declared in the main script from within your function. Actually, there are three specific ways to do this.

Now, I want to get terms straight at the beginning. Variables defined outside of functions are said to be in the global scope, and variables defined inside of functions are said to be in that function’s local scope. I’ll use those terms throughout the rest of this video.

Now, there are actually two different ways to access variables in the global scope from within your function. The first way is to use the special PHP keyword ‘global’.

So, here we have a function that doesn’t take any arguments. Check it out:

function doSomethingGlobal() {
global $var1;
$var1++;
}

$var1 = 10;
doSomethingGlobal();
echo ‘$var1 is ‘ . $var1;

{show output}

With the global keyword, the PHP engine looks for a variable named $var1 in the global scope, and if it finds it, it uses a reference to that actual variable anywhere inside the function that it gets called. So, when I make a change inside the function, that change is reflected when I check $var1’s value later.

{show output}

And if it doesn’t find it, it creates a new entry in the global scope. So, we can actually make new global scope variables from within the local scope of a function this way:

function doSomethingGlobal() {
global $var1;
$var1 = 15;
$var1++;
}
doSomethingGlobal();
echo ‘$var1 is ‘ . $var1;

So here $var1 isn’t declared before the function gets called, but after running this function the outer code can access $var1 and get its value.

{show output}

When using the global keyword on multiple variables, I can use just one line by separating each variable name after the global keyword with commas.

There is another way to use global variables however, and that’s by using what are known as super-globals. These are arrays that are available in all contexts. However, there’s only one super-global array that I want to talk about here. Others will be introduced in later videos as we look at topics where they’re relevant.

$GLOBALS;

$GLOBALS, in all caps, is an array containing all of the global-scope variables in your script. In order to access a variable in the global scope from within the local scope of a function, use the name of the variable as a key, and the value in $GLOBALS will be the value of the variable it refers to. So, let’s rewrite our function again, this time using the $GLOBALS super-global array:

function doSomethingGlobal() {
$GLOBALS[‘var1’]++;
}

{show output}

Basically, all I’ve done is treat $GLOBALS[‘var1’] as though it were the variable, $var1, and then incremented it. The other cool thing about this, is that just like using the global keyword, using the $GLOBALS super-global lets me create new variables in the global scope:

function doSomethingGlobal() {
$GLOBALS[‘var1’] = 10;
}
echo ‘$var1 is ‘ . $var1;

{show output}

So, that’s how global variables work. In later videos we’ll look at other super-global arrays that are useful for different tasks, but all of them can be accessed in any context without using the ‘global’ keyword.

The last method for accessing a global variable inside a function’s local scope is through what’s called ‘pass-by-reference’. I mentioned the reference operator, the &, briefly in the video on foreach loops. You may recall that by placing an & in front of the name assigned to each value as you iterated over an array, your loop could actually change the values in the array. Well, you can use the same operator in the context of your functions’ argument lists, and it gives you the same ability – that is, you can alter the variables passed into your function, and the changes will be reflected in the global scope.

Technically, passing arguments by reference has nothing to do with variable scope, but it’s an important enough topic that I don’t want to move on before talking about it. When you call a function with a variable, as opposed to a literal, unless that variable is an object (and we talk about objects in a later chapter, so don’t dwell on this if you’re not familiar with them), but unless it’s an object, the variable that your function actually uses is the passed variable’s value, and not the passed variable itself. This is an important point, because it means that, as we’ve already seen, if you change the value of that variable within the function, nothing about the variable you sent from the line that called your function will be affected. That’s how things work normally. In programmer terms, we refer to this type of function call as ‘pass-by-value’.

Here’s a simple example of what happens when you change a variable within a function under a normal case:

function doSomething($var1) {
$var1++;
}

$var1 = 10;
doSomething($var1);
echo ‘$var1 is ‘ . $var1;

{show output}

Note that nothing changed about $var1. That’s because the two instances of $var1 exist in two different PHP symbol tables. However, PHP also supports something called ‘pass-by-reference’. This is what you use when you do want a change inside a function to affect a variable that was sent to the function. In order to do this, just put the reference operator, the &, inside your argument list in front of any variable you want passed by reference. Watch what happens:

{place & in front of $var1 in function argument list}

{show output}

So, what just happened? Well, the two instances of $var1 are still part of two different scopes. However, inside the function, the $var1 it uses is actually a reference to the first variable. So as far as the function is concerned, it can use its variable the exact same way as it did before when it was just passed by value, but now, if the function makes a change to its copy of $var1, the original $var1 also gets affected.

And by the way, I only named the variables the same to help make the concept easier to understand, but I can name it whatever I want inside the function and it’s still a reference to whichever variable was passed in through the function call:

{change $var1 in function to $someVar}

{show output}

See? Makes no difference what I call it – it’s still a reference.

However, even when passing by reference, PHP is still keeping the variables in two separate symbol tables, which is made a little more obvious when I can change its name.

Using the reference operator, it’s also possible to get a reference to a variable in other contexts. Let’s look at a final example:

$var1 = 10;
$var2 = $var1;
$var2++;
echo ‘$var1 is ‘ . $var1;

{show output}

Notice, $var2 is just a copy of the value and type in $var1, and not a reference to $var1 itself. Now, with the assignment operator watch what happens:

$var1 = 10;
$var2 = &$var1;
$var2++;
echo ‘$var1 is ‘ . $var1;

{show output}

This time, $var1 actually got updated too. And that’s because $var2 isn’t a copy of $var1’s value, but a reference to $var1. And when $var2 changes, it affects $var1.

If you want to de-reference your variables, you can use the special PHP function ‘unset’. It will set a variable to null without affecting the other variable:

$var1 = 10;
$var2 = &$var1;
unset($var2);
echo ‘$var1 is ‘ . $var1 . ‘<br>’;
echo ‘$var2 is ‘ . $var2;

{show output}

$var1 = 10;
$var2 = &$var1;
unset($var1);
echo ‘$var1 is ‘ . $var1 . ‘<br>’;
echo ‘$var2 is ‘ . $var2;

{show output}

February 12 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Creating custom functions

As programmers, we often find that we’re performing the same logic at different times in a number of different places. So, to simplify our code PHP lets us define our own custom functions.

A function is a short-hand way of telling PHP to perform a series of steps we’ve defined in advance. A function can accept 0, 1, or multiple arguments as input, and can optionally return one value as output. Of course, if you need to return multiple values, you can bundle them together in an array and return the array.

Here’s the basic syntax:

function someFunctionName($arg1, $arg2, $arg3) {
//some logic
}

Unlike variables, our custom functions can be declared lower down in the execution path than where they actually get called. But this is true only if the function is guaranteed to be defined. If you place your function declaration inside any sort of conditional logic branch, its definition must be processed higher up in the code than any calls to it.

Another thing to notice, your function name must be unique, and it is not case sensitive. So if we have a function like SomeFunctionName somewhere else, then declaring ours is going to cause a fatal error. Not only can you not name your own functions the same, but you can’t use the names of any of the PHP library of built-in functions.

Back to the example though, let’s add some logic so our function does something:

function someFunctionName($arg1, $arg2, $arg3) {
$sum = $arg1 + $arg2 + $arg3;
return $sum;
}

To call it, I just write:

$result = someFunctionName(3,4,5);
echo ‘return value is ‘ . $result;

{show output}

What happens here is that my function call includes the values 3, 4, and 5. And when my function gets run, 3 will be used for $arg1, 4 will be used as $arg2, and 5 will be used as $arg3. It adds them together and returns their sum to the statement that called it, where it gets assigned to the variable $result. However, those variables only have meaning within our function. If we try to use one of them outside the function, PHP treats it like a completely separate variable.

{below call to someFunctionName add: echo ‘$arg1 is ‘ . $arg1;}

{show output}

In addition to a type and a value, PHP variables also have what’s called a scope. It’s sort of like their jurisdiction, to use a law enforcement analogy. Within their scope, they have a value, but outside of it, they have no identity. Once you define a function, all the variables used in there, whether from the argument list or ones you declare inside the logic of the function itself, they are completely isolated from the rest of your script. We refer to them as being in the function’s local scope. You can declare variables with the same names outside the function, but they will be totally different, because variables in the main script are said to be in the global scope. And the value of a variable in the global scope will have no bearing on the value of a variable within a function’s local scope. And the variables in the local scope of one function will be completely independent of the variables in the local scope of another function. However, there are ways around this, and they’re the subject of another video.

Anyway, that’s why functions will often have an argument list – so they can get data from the script to perform their logic on, since they can’t access outside variables directly. And you can see that in this case, the function returned the value 12, since that’s the sum of 3, 4, and 5.

And by the way, as you may have guessed already, calling the function, just like with picking a unique name for it, is not case sensitive. For readability, it is strongly recommended that you always call it with the same case characters for the name, but PHP does not enforce this.

{change function name without changing call}

{show output}

Now, my function definition specifies that it should receive 3 arguments. But watch what happens if I try calling this function with only 2 arguments:

{modify code}

{show output}

Since I defined my function as taking 3 arguments, when I only passed 2 I got that warning. It can keep going, but PHP is telling us that there’s a problem with this. One way to get around that warning is with a special operator in PHP, the @ symbol. If I place it on the line that will trigger a warning, the warning is suppressed. But if we really want to make an argument optional, there’s a better way to do that, and that’s by altering the argument list itself, so that PHP knows an argument is optional.

function someFunctionName($arg1, $arg2, $arg3 = 0) {

When PHP looks at this, it sees that if we omit the 3rd argument, it can still execute the function successfully because it knows that it can just use 3 as a default value in its place.

{show output}

Default values can be any of the simple types, like ints, floats, strings, and booleans, or they can also be arrays or nulls. What you cannot use for your defaults are variables. However, you can use constants, and we’ll look at that more in another video.

As a rule, you should only place your default arguments in the right-hand side of any argument list. Otherwise, any default value to the left of a required value will never get used. If I made my first argument required, I’d still have to pass something for the first argument in order to enter the second and third arguments, assuming they were required. And whatever I passed, even if it was just a null, would always take precedence over the default, so the default would never actually be used.

Now, we’ve seen what happens when we call one of our functions with too few arguments, but what if we call it with too many?

$sum = someFunctionName(3,4,5,6);

{show output}

Notice, nothing changed. PHP doesn’t care if your script passes more arguments than a function says it needs, it only complains if you pass fewer. You can pass a whole slew of arguments to a function that doesn’t have any in its definition. And if you want to see all the arguments that were passed, PHP provides a special set of built-in functions that you can use to do this.

Let’s modify our function a little bit:

function someFunctionName($arg1, $arg2, $arg3) {
if(func_num_args() > 3) {
$sum = array_sum(func_get_args());
} else {
$sum = $arg1 + $arg2 + $arg3;
}
return $sum;
}

Now, don’t get overwhelmed, I realize I’ve just introduced you to 3 new functions here, as well as another way to use functions. The first thing I want to point out is the fact that I’m using the return value of 2 of these functions directly without first casting their return values to a variable. When used this way, we refer to this technique as indirect referencing. PHP supports it just fine. It’s very handy.

As for the PHP built-in functions we’re using, the first one is func_num_args. When called from inside of a function, all it does is return the number of arguments that the function was called with.

The second built-in PHP function, func_get_args, when used inside a function it returns an array containing all of the arguments that were passed to this function.

The last built-in PHP function is one of several we look at together in a later video. Basically, it takes an array, tries to treat all of its values as numbers, and returns their sum total.

So basically, all I’m doing with this revised logic is saying that if our function gets called with more than 3 arguments, just add them all together instead of only adding together the first 3. So, now let’s see how this changes our output:

{show output}

So, obviously the 4th value is now included in that total. And in fact, we can go back and really simplify this function if we want to:

function someFunctionName($arg1, $arg2, $arg3) {
return array_sum(func_get_args());
}

By the way, before I close the video, I didn’t show an example of it, but functions do not need to return a value. That’s entirely optional. Some functions will just print out a fragment of an HTML page, and that’s totally fine. Others might do some specific action like write something to a file or alter some record in a database. There are lots of useful things functions can do without returning anything.

Now that you’ve learned about functions, you’re well on your way to creating some really useful and re-usable code.

February 12 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Control Structures, part II

In a previous video, we looked at using logical branching structures to control which statements get executed in your code and which get skipped, depending on your data. In this video we look at one more way to control your code’s execution path – looping.

Personally, I’m a huge fan of looping code. One of my pet peeves is when I come across someone else’s code where they’re doing the same thing over and over for line after line after line, where they clearly could have just used a loop to get the same result.

There are actually 4 different looping structures that PHP supports. The first is called the ‘for’ loop. Here’s the basic syntax:

for($var1 = 0; $var1 < 20; $var1++) {
//code goes here
}

That’s the typical example anyway. The ‘for’ declaration is followed by a 3-part expression in parenthesis. The way this particular setup will work is by setting a variable called $var1 to be 0, incrementing it by 1 each time it goes through the loop, and when it’s no longer less than 20, the loop ends. So, this loop will run 20 times, unless some instruction inside the loop causes $var1’s value to change in some other way, or else exit the loop prematurely.

While going through the loop, the code has access to the current value of the $var1 variable.

Here’s a simple example:

for($var1 = 0; $var1 < 20; $var1++) {
echo ‘I am on loop number ‘ . $var1 . ‘<br>’;
}

{show output}

And you see it’s just 20 lines in ascending order.

Now, a word of caution about loops. If your condition can never be false, then you’re going to get an infinite loop. In practical terms, that’s not quite as bad in PHP as in most other languages. The PHP process gets an execution time limit, 30 seconds by default, and once it takes longer than that to finish, the server kills it. But still, you should never have an infinite loop on purpose.

Before we move on, I want to take a closer look at the three statements inside the for declaration. The first is just a base condition that gets run once just before the loop starts.

The second statement is like the code in your ‘if’ declarations. If it’s true, then the code will run. If it’s false, then the loop is finished and the code execution resumes on the line immediately after your code block.

The final statement is going to be run once at the end of each loop.

A fairly common use for the ‘for’ loop in most languages that have it is iterating over arrays. Assuming your array has integer indexes, you just use the loop counter variable, in this case $var1 as your key to access each value in turn. However, in PHP, the language gives you a specialized control structure just for looping over arrays, called the ‘foreach’ loop. And that’s what we’re going to look at next here.

So, starting with an array ‘$array1’, I use the special syntax below to iterate over it, and assign each of the array’s values to the variable $var1 in turn. So, as I’m going through the loop, my code will be able to act on every value in the array just by referencing $var1.

$array1 = range(0, 19);
foreach($array1 as $var1) {
echo ‘I am on loop number ‘ . $var1 . ‘<br>’;
}

{show output}

The range function is just one of those handy ones built into PHP. In this case, I give it a minimum and maximum value, and it gives me an array with each integer in that range as its values.

Foreach has another way of being invoked though, and that lets you get both the keys, and the values:

foreach($array1 as $key => $value) {
echo “Key $key has value $value<br>”;
}

{show output}

This is particularly useful with associative arrays, where both the key and the value are significant. It’s also something you can’t do just iterating over an array in a for loop.

Now, occasionally, you’ll want to actually change the values of an array as you iterate over them. It’s not possible to change the keys, but to change the values, you use a special operator – the single &:

foreach($array1 as &$value) {
$value *= 2;
}
unset($value);
foreach($array1 as $key => $value) {
echo “Key $key has value $value<br>”;
}

So, this bit of code is going to double each value in the array. The call to unset at the end there is important because after the final loop, $value is still connected to the last value in the array. Using unset just unlinks that variable from the array, and avoids the risks of weird or unexpected behavior. But we talk about variable references in a later video, so I won’t go into more detail here.

{show output}

By the end of loop, the values in $array1 will all be doubled.

The next two loop types I want to introduce you to are the while and do while loops. These are sort of like for loops in a sense, except they only have the conditional expression. There’s no initializer and no expression that gets run with each loop. With the while loop, so long as its condition evaluates to true, it will continue to run. The code within the block is responsible for changing the data such that the condition no longer evaluates to true. Here’s a simple example:

$var1 = 10;
while($var1 > 0) {
echo ‘The current value is ‘ . $var1 . ‘<br>’;
$var1–;
}

{show output}

While $var1 is greater than 0, it prints out its value and then decreases it by 1. Eventually the while condition is no longer true and the code exits the loop. In the case of the while loop, if the condition is false to begin with, the loop will never execute. The difference with the do while loop is that you are guaranteed to run your loop at least one time. Instead of evaluating the condition, and then running the code if it’s true, it runs the code, and then checks the condition to determine whether to run it again.

{change $var1 = 10 to $var1 = 0}

{show output}

See? As a while loop, it didn’t run. Now if we change it to a do while loop, all we do is place the ‘while’ statement, with its conditional expression, after the closing brace. And we put the word ‘do’ up here in front of the opening brace:

{modify loop}

{show output}

The loop code ran once, and then since the condition was false, it didn’t run again.

The last thing I’m going to show you when it comes to loops is how to use the special ‘break’ and ‘continue’ statements. We already got a look at the break statement in the context of ‘switch’, and in the case of loops it does the same thing. When your script hits a break statement for whatever reason, it exits whatever loop (or switch statement) it happens to be in:

$var1 = 10;
while($var1 > 0) {
echo ‘The current value is ‘ . $var1 . ‘<br>’;
if($var1 == 5) {
break;
}
$var1–;
}

If you’re inside of two or more loops, and need to break out of all of them, you can use the break statement followed by the number of loops and switches you want to break out of:

$x = 32;
for($i = 0; $i <10; $i++) {
for($j=10; $j > 0; $j–) {
if($j*$i == $x) {
break 2;
}
}
}
echo “($i, $j)”;

On the other hand, sometimes you don’t want to exit a loop entirely, but you do want to skip to the next iteration. Well, in that case continue is what you need. In the case of a switch statement, since there is no iteration taking place, it will perform exactly the same as a break. But in a loop, it simply halts the current iteration and skips ahead to the next one, if one exists. If there are no further iterations to perform, the loop simply ends:

for($i = 0; $i<30; $i++) {
if($i % 4 == 3) {
continue;
}
echo ‘I am on iteration #’ . $i . ‘<br>’;
}

Like break, continue can also be used with multiple loops. Suppose I have a couple of nested for loops. If the inner loop hits ‘continue 2’, then it’ll break out of that loop completely, but then begin the next iteration of the outer loop.

That concludes the lesson on control structures. They’re a little tricky the first time you see them, but they’re indispensable in good coding.

February 11 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Control Structures, part I

Now that we’ve taken a look at how to build variables, we’re going to look at how to build the basic logic, called the control structures, that let you manage how your script is executed. Without any control structures, your code will simply execute each line until it reaches the end. But usually you want to change the script execution path based on your data. Control structures give you that flexibility.

The first control structure is called the if statement. All it does is evaluate an expression, and if that expression is true, it invokes the code in its branch. If not, its branch gets skipped.

We define it like this:

if(expr) {
//code to execute
}

The braces define your branch, and they can include as many lines as you need. The parenthetical statement between the word ‘if’ and the opening brace is your test expression.

So, here’s a pretty simple example:

$var1 = true;
if($var1) {
echo ‘I am the true branch!’;
}

{show output}

Because $var1 was true, we went into the branch and saw the somewhat pompous output from it, but if we change $var1 to false, our output is blank:

{modify $var1}

{show output}

Now, if we want, we can define another branch that only gets executed when the expression is false. And we do that with an ‘else’ branch, like so:

if($var1) {
echo ‘I am the true branch!’;
} else {
echo ‘I am the false branch!’;
}

{show output}

This time, since $var1 was still false, we ended up going through the code in the else branch, resulting in the output we see here.

Now sometimes, if and else are insufficient. They only give you the ability to test for two different outcomes. But what if you want to create more than two possible outcomes? If that’s what you want, you can create one or more ‘elseif’ branches. An elseif branch can be created with or without a space between the words ‘else’ and ‘if’ – both work. Just follow it with an expression, the same as declaring an ‘if’ branch, and then define your branch inside braces again:

$var1 = 1;
if($var1 > 0) {
echo ‘$var1 is greater than 0’;
} elseif($var1 == 0) {
echo ‘$var1 is 0’;
} else {
echo ‘$var1 is something else’;
}

{show output}

Now, if both your ‘if’ condition and your ‘elseif’ condition are true, only your ‘if’ branch will be run. PHP stops checking your test expressions after it finds one that evaluates as true. Once it does, it runs that branch and then continues executing below the close of your entire control structure.

As far as the branches go, you’ve got to have an if branch, but the else and else-if branches are entirely optional. And you can have as many elseif branches as you like, but you can only have one else branch connected to an if branch, and it always has to come at the end after any elseif branches you may have defined. Logically this makes sense since else just gets run if no if or elseif branch runs. Another else or a follow-on elseif branch just wouldn’t make any sense.

Now, let’s imagine you have a situation where you’ve got lots of if and elseif branches testing one variable for a whole range of possible values. As in, if $var1 is 1 do this, else if it’s 2 do this, else if it’s 3 do this, and so forth. For this situation, PHP provides us with another control structure called a switch statement.

{show ready-made example script with switch}

In the opening of the switch statement, I tell the script which variable I’m testing the value of. Each of the case statements then provides a value to test that variable against. If the variable’s value matches the value of the one in the case statement, it executes that statement. It continues execution until it encounters a break. If I remove the break,

{remove break from the case that is going to match}

{show output}

it will execute the next case’s instructions even though the variable doesn’t match it’s comparator. Here you can see that that’s happened. Sometimes, I actually want that behavior, for instance when I want the same action to happen for more than one case. But most of the time we want to remember that break.

There’s a couple other important things to keep in mind about the switch statement. First, you can only compare simple types – like floats, strings, and ints. Second, the comparison is loose, so the string ‘123’ matches the int one hundred twenty three. Basically it’s the double-equal sign comparison instead of the triple-equal sign. And third, you can do comparisons with variables and expressions, so long as they evaluate to a simple type.

Alright, now the next thing I want to show you is the default statement:

{show example}

This is basically your else statement with a new name. This statement’s code will get used if none of the cases above it match. You set up a default statement whenever you want to make sure that some code gets executed no matter what:

{show output}

There is one last secret with switch statements, and this is something that not many PHP developers even know about. Those case statements can actually do more than just test whether your test variable equals some value. You can actually do any of the logical tests between a variable and a simple value. This is great when you have, say, a float, and you need to build case statements that test not for a precise value, but for an entire range. To do that, you place your test in parenthesis after the word ‘case’. You can only test the variable you declared in your switch statement, and again, you can only test it against a simple type value, but now you have the freedom to test more than just straight “$a == 2” or something like that. Here’s an example:

{show example}

{show output}

That’s it for part I of control structures. In the next video we’re going to look at loops.

February 09 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

PHP Constants, Magical and Otherwise

We’ve already talked about PHP variables, now we’re going to look at PHP constants. As the name suggests, once you define a constant, its value doesn’t change, and your script can’t un-define it.

PHP comes with many constants built-in for use in situations that require you to interact with certain built-in functions. Generally, these constants are just integers that have no special significance outside their special cases where they’re needed. Here’s where you can find a complete list of these pre-defined constants. {show website} A few more seem to get added with every new release of PHP, so depending on how much time has passed from when this video was recorded to when you started watching it, there could be any number of new constants added to the language. The best way to find out is to check the manual.

Technically, a constant can hold the value of any scalar type. That means ints or strings, which is what you’ll usually see, and also floats and booleans – no arrays or objects. Also, unlike a variable, constants are always global in scope, so it’s important to make sure that you don’t define the same constant more than once. If you try to define a new constant with the same name as one that already exists, you’re going to trigger a fatal error.

Why might you want a constant? Well, let’s look at what a constant gives you. Here’s a simple example:

define(‘MY_FIRST_CONSTANT’, 33);

Notice I chose to use all upper-case letters for my constant’s name. Much like variables, all constants must begin with either a letter or the underscore character, and may only contain letters, the underscore, and numbers in their labels. The names are also case-sensitive, so technically there is no built-in reason to prevent me from using lower-case letters. However, convention states that constants should have descriptive upper-case names, in order to make it obvious that they’re constants.

Now, as far as this one goes, I just picked a random number out of my head and set it as the value. The most important part about a constant isn’t usually the value so much as the name. By having a meaningful name like this, I can incorporate it into my code’s logic. If I want to control what happens in a particular situation, I can create a constant that describes the situation I’m watching for, test whether or not a variable with that value is present, and control what happens next accordingly.

And since a constant’s name is meaningful to a human, when you see it, it ought to be clear what it’s intended to do. Here’s a practical case:

{show example code}

This particular example uses a constant, passed by some calling script, to determine what test to use in order to compare two values. Since GREATER_THAN is more meaningful than the number 3, constants in this situation make it easier to keep the code organized.

Like I said earlier, you want to make sure you don’t define the same constant more than once. To assist you in that, PHP gives you a function called ‘defined’. Call it on a string, and it will return true if that constant has been defined by that point in the script’s execution, and false if it hasn’t.

{show example code and output}

And if for some reason, you ever need to use a variable to hold the name of a constant, and you want to get that constant’s value, PHP provides a function called ‘constant’. Call it on your variable, and it’ll output the value of the constant it refers to, if any.

{show example code and output}

You’ll encounter constants from time to time as you work with PHP’s library of built-in functions, whether you choose to define your own or not. But some of the most interesting constants built into PHP technically aren’t constants at all. These are the magic constants.

All of the magic constants use a similar syntax – 2 underscore characters, followed by an upper-case name, and then two ending underscores. And they get their name from the fact that they look like constants, but their values depend on the contexts in which they’re used.

Here’s the first one:

__LINE__

I can place this magic constant into my script, and wherever it is, that line number, that’s its value. Check it out:

{show example code}

{show output}

Pretty cool, huh? Practically, the most common use of __LINE__ is in debugging. There typically isn’t much call for revealing what line number in your script you’ve reached when you’re in a production environment. But when you’re looking for a bug, it can be very helpful to see how far you’ve gone.

The next magic constant is __FILE__. This time, it takes on the value of whichever file I place it in:

{show example code}

{show output}

And see if I rename the file, like so:

{show output}

It takes on the new filename. Neat, huh? Once again, mainly a tool for debugging.

If what you need is the directory of the current file, you can use __DIR__. This is a new addition to PHP 5.3. For older PHP scripts, you’ll often see:

dirname(__FILE__)

which has the exact same value. I guess the PHP engineers just decided it was time to simplify things. Typically you use it for things like searching a directory or adding a value to the include path.

There’s also a magic constant to get the name of the function it resides in, assuming it resides in one:

__FUNCTION__

I know about this constant, but I’ve never used it for anything, and I’m not entirely sure when it could be useful. Still, there it is.

The last 3 magic constants that exist as of this video deal with topics we haven’t covered yet. But here’s the PHP manual page that talks about them.

{show website}

To find it for yourself, just go to PHP.net and search the online documentation for “magic constants”.

February 09 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | 2 Comments »

PHP Strings

Probably the most used data type in any PHP script is the string. Fundamentally, a PHP string is just a sequence of characters. However, there is more than one way to define a string, and how you define it turns out to be very important.

The first way to define a string, and the way I’ve consistently been defining them in the videos up until this point, is inside single-quotes. And with single-quotes, whatever you type inbetween your quotes is the exact value of the expression, with one exception. You can escape apostrophes inside single-quotes by using a backslash.

$quoted = ‘I don\’t break’; //$quoted gets value “I don’t break”

Double-quoted strings, on the other hand, are far more interesting in PHP. With double-quoted strings, you can embed variables that will form the contents of the string based on their value when the string’s expression is evaluated. So for instance:

$color = ‘green’;
$useVar = “I see a $color truck”; //$useVar now says ‘I see a green truck’
echo $useVar;

Now, if $color wasn’t set before the string expression was evaluated, your message would just be ‘I see a  truck’.

Sometimes, you want a double-quoted string to contain a $ without getting evaluated. PHP knows that if a $ is by itself, or if it’s followed by numbers rather than letters, to leave it as a $ when evaluating the string. However, if you want to see the literal string ‘$color’ inside your double-quoted string, you just need to escape your $ with a backslash, like this:

$useVar = “I see a \$color truck”;

Escaping is particularly important with double-quoted strings. To get a literal double-quote, just place a back-slash in front of it. Same to get a literal backslash.

Something else you can do, however, is use the backslash to get a newline, carriage return, or a horizontal tab.

In order, those are:

“\n”;
“\r”;
“\t”;

This is especially useful when you’re sending your output to a file or in an email, and you need to end your lines with the appropriate line-termination character. When outputting your contents to the web of course, your audience will be much more concerned about whether you use the <br> tag, since new-lines don’t generally show up. Although, even when outputting HTML, having new-lines in places where they make sense can make your HTML much easier for a human to read.

If your double-quoted string needs to have a variable show up right in front of characters, you can use braces to let the PHP engine differentiate between the variable and the string content. For instance:

$type = ‘dodge’;
$message = “Let’s go play {$type}ball tonight!”;
echo $message;

Without the braces, PHP would look for a variable name $typeball, and on failing to find it, would replace it in with the empty string.

With double-quoted strings, you can also insert values from arrays, like so:

$var1 = array(‘one’=>’orange’, ‘two’=>’banana’);
$message = “I am hungry for the $var1[two] milkshake”;

Notice, I don’t have to use single quotes around the key when I’m in the string. As a matter of fact, if I use the single quotes around my array key, I’ll get a parse error. However, if I use braces, I can stick the single quotes in.

$var1 = array(‘one’=>’orange’, ‘two’=>’banana’);
$message = “I am hungry for the {$var1[‘two’]} milkshake”;

Now a point I want to make about single quotes versus double quotes, and it should be pretty obvious. Since double-quotes require an extra step from the interpreter before it can evaluate them, there’s a slight performance penalty. If all you need are literal strings without variables or special characters, use single-quoted strings. They’re just a little bit faster. It’s not a big deal, but it’s good practice to pick the faster option when you can.

Moving on, there are 2 other ways to define strings. They’re called NOWDOC and HEREDOC. They look pretty similar, and they’re handy when you need to put a long block of text into a variable, but they can get you into trouble if you aren’t careful.

First, NOWDOC. NOWDOC begins with three ‘less than’ signs together, followed by an upper-case, single-quoted string. You place any text you want after that opening, and then you end it with the original identifier, without any quotes. Here’s an example:

$color = ‘green’;
$myNowdocString = <<<‘MYNOWDOC’
This short line of text is standing in for a longer line of text.<br>
I see a $color truck.
MYNOWDOC;

The most important warning here is that you must have a newline right after the opening tag, and a newline right before the closing tag. And on the line with the closing tag, there can be no other characters or spaces save for the closing semi-colon. If PHP doesn’t find the exact closing tag it’s looking for, it’ll keep going down your script until it reaches the end, and will throw an error referencing the last line of your file.

What the NOWDOC syntax basically does is act like one single line in your PHP code, but lets you split it across as many lines as you need.

As with single-quotes, your text inside your NOWDOC will be interpreted exactly as it appears, with no need to escape anything.

It should be noted, that NOWDOC was introduced in PHP 5.3. Earlier versions don’t support it.

The last way to define a string is with HEREDOC syntax. And HEREDOC is to NOWDOC what double-quoted strings are to single-quoted strings. Since HEREDOC has been around longer, you can define it by using an opening tag with no quotes. But, since PHP 5.3 and NOWDOC syntax have arrived, the PHP engineers have driven home the single-quoted/double-quoted string parallel pretty hard by enabling you to define your opening tag as a double-quoted string, like so:

$color = ‘green’;
$myHeredocString = <<<“MYHEREDOC”
This short line of text is standing in for a longer line of text.<br>
I see a $color truck.
MYHEREDOC;

Since it’s analogous to a double-quoted string, that means you can embed variables and special characters in it, with all the same rules that apply to double-quoted strings. Obviously one of the main advantages to NOWDOC and HEREDOC over quoted strings is that there’s no need to escape quotes, and blocks of text can be easier to read in many cases.

When you need to combine strings together, you use a period. In PHP terms, the period is referred to in this case as the “string concatenation operator”. If you stick it in the middle of two string, or a string and something that can be converted to a string, the entire expression takes on the value of the first string joined to the second.

$color = ‘green’;
$joinedString = ‘I don\’t need any variables’ . “, but I see a $color truck.”;

And it’s not something you see everyday, but concatenation works on HEREDOC and NOWDOC strings as well. Just remember to have the period on a different line from your string ending tag.

Lastly, I want to point out that you can combine concatenation and assignment into one step. Suppose you have a variable named $string1 and you need to append some other string to the end of it. Well, you could do:

$string = $string . ‘ Now make it longer!’;

But you could get the exact same result by doing this:

$string .= ‘ Now make it longer!’;

PHP also supports a number of special functions for working with your strings, and that’s going to be the topic of a later video. In the meantime, you should now have all the tools you need to start using strings effectively in your own scripts.

February 08 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | No Comments »

Next »