Official website for Web Designer - defining the internet through beautiful design
FOLLOW US ON:
Author: Steve Jenkins
24th June 2013

Beginner’s guide to PHP part 2

In part 2 of our Beginners guide to PHP there is a look at arrays, classes, storage and a collection of resources.

Beginner's guide to PHP part 2

A BEGINNERS GUIDE TO PHP – part 1

Arrays

Fast-forward a few months, and now the nightclub is doing better than ever. In fact, it’s doing so well to the point that the bouncer can’t keep up. His job might be easier if he could instead filter through a group of people at a time.
Think of an array as a container for related data. You could even refer to it as a list: a list of tweets, a group of family members, an array of birth dates.
An array in the latest version of PHP (5.4) may be defined using a comma-separated list within brackets, like so:

001 $group = [1985, 1990, 1992, 1997];

This single ‘$group’ variable now contains multiple birth dates. Values within it may be accessed by specifying an index, such as ‘$group[0]’. Arrays are what we refer to as being zero-based. In translation, this means that the first item, or key, in the array will have an index of zero. As such, to access the 1992 value, you would reference ‘$group[2]’.
Now, the bouncer can rapidly filter through these birth dates, and calculate whether to allow the person in, or reject them. A ‘foreach’ statement may used for this type of filtering.

001    $group = [1985, 1990, 1992, 1997];
002    foreach($group as $yob) {
003        if (isAdult($yob)) {
004            echo ‘Come on in!’;
005        } else {
006            echo ‘Please leave now, before     I     call your mother.’;
007        }
008    }

Notice how the bouncer declares that the birth year ‘foreach’ person in the ‘group’ should be contained within the variable, ‘$yob’. Next, as he did before, he passes that value off to the ‘isAdult’ function, and proceeds accordingly.
It’s possible, though, that the bouncer may become slightly confused when he doesn’t have a link between the person’s year of birth and their name. PHP also allows for associative arrays, which provide the necessary functionality to associate a given value with a key. Check out the example we’ve listed below to explain this feature:

001 $group = [
002        ‘John’  => 1985,
003        ‘Susan’ => 1990,
004        ‘Joe’   => 1992,
005        ‘Sara’  => 1997
006    ];
That’s better. As an added bonus, the bouncer can be a bit more friendly to the person, now that he knows his or her name.

001    $group = [
002        ‘John’  => 1985,
003        ‘Susan’ => 1990,
004        ‘Joe’   => 1992,
005        ‘Sara’  => 1997
006    ];
007    foreach($group as $name => $yob) {
008        if (isAdult($yob)) {
009            echo “Come on in, $name!”;
010        } else {
011            echo “Please leave now, $name,     before I call your mother.”;
012        }
013    }

When storing strings within double quotes, you may nest variables rather than use concatenation. This can lend itself for a more readable syntax.

Classes

Object-oriented programming is well beyond the scope of this beginner tutorial, but, nonetheless, classes deserve a mention. For now, think of them as simple containers for related properties and methods. For instance, here’s how a class that represents a single person might look:

001    class Person {
002        public $name;
003        public $age;
004        public function __construct($name,     $age)
005        {
006            $this->name = $name;
007            $this->age = $age;
008        }
009    }

Notice that ‘__construct()’ method? This is referred to as a magic method, and will be triggered immediately upon instantiation. When this method fires, it will accept a name and age, and then attach that to the object. To use this class, try:

001   $me = new Person(‘Jeffrey’, 28);

This will create a new instance of the ‘Person’ class. This instance, which is stored in the ‘$me’ variable, can be referred to as an object. Now, there’s nothing prohibiting you from creating multiple instances of this class – and, in fact, in real-world projects you will! The class is just a blueprint.
At this point, however, the class isn’t overly useful. Let’s add a method, or function, to designate the spouse of a person.
001    class Person {
002        public $name;
003        public $age;
004        public $spouse;
005        public function __construct($name,     $age)
006        {
007            $this->name = $name;
008            $this->age = $age;
009        }
010       public function marry(Person $spouse)
011        {
012            $this->spouse = $spouse;
013        }
014    }
015    $me = new Person(‘Jeff’, 28);
016    $her = new Person(‘Allison’, 28);
017    $me->marry($her);

This modified code now includes a ‘marry()’ method that will update a ‘$spouse’ property on the object. Now, you have a direct link between the two people.
If a method argument is preceded by a class name (‘Person $spouse’), referred to as type hinting, this designates that the parameter must be an instance of the given class, or an error will be thrown.
To fetch the name of my spouse, you could write:

001    echo $me->spouse->name; // Allison

The concept of object-oriented programming goes much deeper than this, but keep it simple for now. It helps to think of classes as singular nouns: a tweet, or user, or customer, or file.
True appreciation for this type of pattern will only come with time.

Hands-On

Put your new-found skills to the test. How might you go about registering and displaying tweets for a user on the page? Well, the first step might be to define a class that represents a single ‘Tweet’. This class should store properties for the body of the tweet, as well as its publish date. Additionally, it should ensure that the body of the tweet does not exceed 140 characters. Here’s a first stab at such a class:

001    class Tweet {
002        public $body;
003        public $pubDate;
004        public function __construct($body)
005        {
006            $this->setBody($body);    
007            $this->setPubDate(new DateTime);
008        }
009        public function setBody($body)
010        {
011            if (strlen($body) > 140) {
012                throw new         013     InvalidArgumentException;
014            }
015            $this->body = $body;
016        }
017        public function setPubDate(DateTime     $date)
018        {
019            $this->pubDate = $date-    >format(‘Y/    m/d H:i:s’);
020        }
021    }

Though it may initially seem overwhelming, give this code snippet a bit of study, and try to understand what is happening each step of the way. You may find that it’s quite readable!
One interesting new piece of functionality stems from the ‘setBody’ method. If the text provided exceeds 140 characters, which we can calculate using PHP’s ‘strlen’ function, then we should take exception to that, because it breaks the rules of a tweet. An exception can be thrown using the syntax, ‘throw new ExceptionType’.
Now that we have a decent-enough container for a tweet, we can create a couple of tweets, store them in an array, and then, ultimately, render them on the page, using a ‘foreach’ statement.

001    $tweets = [];
002    # add two new tweets to the array
003    $tweets[] = new Tweet(‘Going to the     store.’);
004    $tweets[] = new Tweet(‘Back from the     store!’);
005    # Filter through, and display on page.
006    foreach($tweets as $tweet) {
007        echo “<h2>{$tweet->body}</h2>”;
008        echo “<p>Posted on: {$tweet-    >pubDate}</    p>”;
009   }

Upon viewing the output in the browser, you should see something along the lines of:

Beginner's guide to PHP part 2

This is excellent stuff so far. However, the next question that you need to ask yourself is: how do we save those tweets?

Storage

So far, you’ve learned the essentials: variables, conditionals, functions, arrays, classes. There’s more to cover, but you should research that on your own, as the need arises. The next step in your learning is persistence. For example, how might you keep a log of all tweets? A tweet service that doesn’t ‘remember’ tweets is a terrible one! This is when the idea of databases comes into play.
Think of a database table as an Excel spreadsheet. It can have any number of fields, such as the person’s name, age, or mailing address. However, PHP doesn’t provide this sort of storage natively. Instead, the most common option is MySQL which is the world’s most popular open-source database.
Installing MySQL doesn’t fall within the scope of this tutorial. Instead, you can check out this tutorial at http://bit.ly/91RImE on Nettuts+ for a complete walk-through of the essentials.
Here’s a simplified example to get you started with securely fetching rows from a database table. Don’t worry if it seems overwhelming. MySQL is your second new language to learn. PHP’s PDO API, as well as the query language, itself, require time to learn.
First, you’ll need a way to connect to the database.

001 function connect() {
002        $conn = new PDO(
003            ‘mysql:host=localhost;dbname=DB_    NAME’,
004            ‘USERNAME’,
005            ‘PASSWORD’
006        );
007        $conn->setAttribute(
008            PDO::ATTR_ERRMODE,
009            PDO::ERRMODE_EXCEPTION
010        );
011        return $conn;
012    }

For the next step, we’ll work on adding in a helper function that will fetch all records from the tweets table. It’s important to pay close attention to the ‘query’ method’s argument, ‘SELECT * FROM tweets’. This is a special language used for querying the database. In this particular case, we’re using the ‘*’ symbol to reference all rows. As such, we’re selecting all rows from the table, called ‘tweets’.
This function prepares the query, and then fetches the complete result set.

001    function fetchTweets($conn) {
002        $stmt = $conn->query(‘SELECT * FROM     tweets’);
003        return $stmt->fetchAll(PDO::FETCH_    OBJ);
004    }

Now, with the stage set, we only need to call the functions, accordingly.

001 # Connect to the DB
002    $conn = connect();
003    # Fetch all rows from attendees table
004    var_dump(fetchTweets($conn));

An easy method that you can employ in order to dump the contents of a variable is through the use of the ‘var_dump’ function. If you pass the output of ‘fetchTweets($conn)’ to this function, upon viewing it in your browser, you’ll see something that looks along the lines of:

The ‘var_dump’ function is helpful for debugging, but for production purposes it’s better to filter through the results, and render them on the page properly. The ‘foreach’ statement, which you’re already familiar with, will handle the job quite nicely!

001    $tweets = fetchTweets($conn);
002    foreach($tweets as $tweet) {
003        echo “<h2>{$tweet->body}</h2>”;
004        echo “<p>{$tweet->pubDate}</p>”;
005    }

Conclusion

As with any skill, writing fluent PHP requires nothing more than your time, patience and practice. It may take hundreds of hours to fully grok, but that’s okay. This is fun, right? It should be!
The best way to learn anything at all is to do it. Build yourself plenty of throw-away projects like they’re going out of style! The techniques that have been outlined in this beginner tutorial will take you through the first phase, but, certainly, as your skills progress, you’ll move on to more advanced topics, such as PHP frameworks, design patterns, and test-driven development.
Persevere with it and you’ll soon find yourself whizzing along and wondering why you ever thought it was difficult to master. Simply keep working and most importantly, have fun!

Five required PHP resources for beginners

Clearly, a magazine article can only serve as a single stepping stone to supplement your learning of PHP. Luckily, there’s also a vast world of training that’s readily available at your finger tips. Never in history has education been so easily accessible.

1. PHP fundamentals
The Tuts+ Premium is a service that specialises in PHP training, covering everything from the basics, such as PHP Fundamentals, all the way up to coverage of modern frameworks, such as Laravel.

2. PHP master
PHPMaster is a weekly tutorial site that, as you might have guessed, specializes in PHP. While much of its content may be a bit advanced for your skill set, it’s one that is worth bookmarking nonetheless.

3. Nettuts+
Nettuts+ is the premier web-development tutorial site. It covers multiple technologies, languages, and frameworks, but since its inception, PHP has been at its core. You won’t find better free education online.

4. PHP Solutions
When it comes to PHP books for beginners, David Powers’ PHP Solutions (available from http://amzn.to/13YRVwm) is a fantastic choice, and with its helpful tips and advice should be required reading for all newcomers.

5. Codecademy
Recently, Codecademy, a website that offers free interactive learning, introduced its PHP track, developed by the community. Though it won’t take you right the way from A to Z, it offers a helpful and fun way to learn a few new tricks and techniques.

  • Tell a Friend
  • Follow our Twitter to find out about all the latest web development, news, reviews, previews, interviews, features and a whole more.
    • Jon Fuller

      i really struggled when following this tut in the mag, any advice would be great