Aug 30 2010

PHP is my favourite programming language of all time. It’s simple when you need it to be, and advanced when you need that extra power. I’m what many people would call an evangelist of PHP. Since starting work at Netbasic, I’ve really gone all out in using object-orientated programming (OOP) with PHP, and nearly everything I do is object-orientated now.

Let’s step back a moment to the title of this article, “PHP Basics”. Isn’t that an indication that this is a guide for beginners? You’d be right in thinking that, and I’m going to go from nearly the beginning. For the purposes of the tutorial, I will assume you know how to set up your own LAMP or WAMP server (and if you don’t there are countless great tutorials on that), and that you know how the internet works and some basic HTML/CSS. I will also assume that you have little-to-no experience of object orientated programming (although understanding OOP in C++ or Java for example would be a bonus!), little-to-no experience of general programming, and no experience of PHP.

The next question you’re probably asking is why am I writing a “PHP introduction” tutorial when there are countless already out there? The answer to that is that I’m trying a different approach that I’ve not seen before. I’m going to start at the object orientated level so that procedural PHP scripting doesn’t even factor into the equation. I’ve done quite a long preamble now with not much in the way of teaching PHP, so we’re going to start now.

Hello Classy World

When starting almost any programming language, you will always start with something called a “Hello World” app. All this app does is write, print, echo or display somehow a string saying “Hello World”. It’s often also used to test an installation works to ensure PHP is performing as expected. So, fire up your favourite editor and create a new helloworld.php file in your web root, and fill it with this basic OOP code:

<?php
class MyClass
{
  function HelloWorld()
  {
    echo "Hello, world!";
  }
}
 
$obj = new MyClass();
$obj->HelloWorld();

Okay, let’s run through what is happening here. We’re creating an object (a class) that is called “MyClass”. Within the scope of the class (indicated by curly braces { and } ) we have something called a “function” that is called “HelloWorld”. Within this “function”, is echo “Hello, world!”. What we have done here is define a class (or object – they’re interchangeable terms in OOP) with a function that echos the string “Hello, world!”.

Back up a sec, what’s a function? And an echo? And scope…

If you’re a beginner reading this, you might be confused already, so I’ll go through a couple of things…

Echo

Echo is a “language construct” (which means it’s an integral part of PHP) that outputs whatever follows it to the browser. If this were a procedural script, doing something like this might result in the browser seeing the words “Hello, world!” in plain text on a plain background.

<?php
echo "Hello, world!";

Echo is fundamental to PHP and you’ll use it a lot.

Variables

Variables are like the memory function on your calculator, but a bit more complex. A variable is a value that is stored in the computer memory for use in your script. Variables in PHP have names, which are defined by the dollar symbol ($). For example, here are a couple of variables:

<?php
$name = "James";
$favourite_hobby = "PHP";
$number_of_toes = 10;

Variables are case-sensitive (meaning $apple is not the same as $Apple), and can only contain letters, numbers and underscores, and can’t start with a number. Using our very limited knowledge so far, we can store a value in a variable, and echo it to the browser:

<?php
$text = "Hello, world!";
echo $text;

What we have done is store the string (a collection of characters – or letters) in the $text variable. You can use variables in many places to replace using actual values (think algebra!), and are extremely important to programming.

Functions

A “function” (in programming) is a group of lines of code that can be executed in your script. An example of a function is something that adds two numbers together – it performs a specific function, and sometimes gives a result back. For example:

<?php
function AddNumbers($a, $b)
{
  $c = $a + $b;
  return $c;
}

The notation for “defining” a function is as above – the word “function” followed by the name of the function (in this example, “AddNumbers” followed by an open parenthesis symbol, some “arguments”. The lines of code contained within the curly braces are what will happen when the function is called. Let us use the function above and combine with our knowledge of variables and echoing values.

$apples = 50;
$oranges = 25;
$fruit = AddNumbers($apples, $oranges);
echo "There are {$fruit} pieces of fruit.";

This snippet has two declared variables – $apples and $oranges – and uses the function AddNumbers to add them together, and output a string with a variable inside (contained within curly braces!) to the browser. There are many more complexities when dealing with functions, especially with some newer PHP 5.3 features, which I will leave out to avoid too much confusion!

You can actually simplify this code already (and more experienced programmers will have noticed this). Spot where I have simplified this a little:

<?php
function AddNumbers($a, $b)
{
  return $a + $b;
}
 
$apples = 50;
$oranges = 25;
echo "There are " . AddNumbers($apples, $oranges) . " pieces of fruit.";

In PHP it is possible to evaluate code in place of creating new variables – we have replaced declaring two variables – $c in the function, and $fruit outside the function. The performance benefit for doing this is arguable, and negligible if at all – not to mention completely out of the scope of this article.

Understanding Objects

Now that we have a basic grasp on a few fundamental principles, we can look at object orientation. You have to look at everything you do in a different way – a way where every object is it’s own entity and serves it’s own purpose. Not only that, but objects can be types of other objects, and there can be many multiples of objects, sometimes containing many other objects.

First ask yourself what is an object in the real world. An commonly used example for understanding objects is Apples and Oranges. An Apple is an object, and the type of object is a fruit. Further classification could say that fruit is a type of food. Let’s represent this in PHP objects using empty classes, and the keyword “extends”.

class Fruit
{
}
 
class Apple extends Fruit
{
}
 
class Orange extends Fruit
{
}

The “extends” keyword basically means class X inherits class Y – it inherits typical characteristics of the “parent” class as it is known. This parent/child relationship is common across all object-orientation, and is an important concept to master. Lets put in some functions into our classes to demonstrate what I mean.

<?php
abstract class Fruit
{
  abstract public function Prepare();
 
  public function __construct()
  {
    echo "You have created an " . get_class($this) . "<br />";
  }
 
  public function Serve()
  {
    echo "You have served the " . get_class($this) . " on a plate.<br /><br />";
  }
}
 
class Apple extends Fruit
{
  public function Prepare()
  {
    $this->Slice();
  }
 
  private function Slice()
  {
    echo "Apple has been sliced.<br />";
  }
}
 
class Orange extends Fruit
{
  public function Prepare()
  {
    $this->Peel();
    $this->SeparateChunks();
  }
 
  private function Peel()
  {
    $this->GrateZest();
    echo "Orange has been peeled.<br />";
  }
  private function GrateZest()
  {
    // grate that zest so we can use it to cook!
    echo "The zest of the orange has been saved for cooking.<br />";
  }
 
  private function SeparateChunks();
  {
    // separate the orange chunks into bitesize pieces
    echo "The orange has been separated into chunks.<br />";
  }
}
 
$my_apple = new Apple();
$my_apple->Prepare();
$my_apple->Serve();
 
$my_orange = new Orange();
$my_orange->Prepare();
$my_orange->Serve();

Woah, this bit of code just got a whole lot bigger! I’ve introduced a few more concepts here, which I’ll go into a little bit more detail about. Firstly though, this code will output something like:

You have created an Apple
Apple has been sliced.
You have served the Apple on a plate.

You have created an Orange
The zest of the orange has been saved for cooking.
Orange has been peeled.
The orange has been separated into chunks.
You have served the Orange on a plate.

Okay – lets have a look at some new key concepts to help understand the above code and how we got to the output.

Instances

When you write a class, you are defining the structure. The “class MyClass” and optionally “extends AnotherClass” tell the PHP interpreter that you are creating the class structure itself – the skeleton if you will. By doing this, you are saying these are the blueprints of how it all works. When you want to actually use a class, you do something called instantiate the class – or create an “instance” of it. Think of this as the physical existence of the object. You can, of course, have many instances. Each of the variables defined below is what is called an instance of a particular class. We use the “new” keyword to identify this by create a new instance of whatever class name follows. You can interact with these instances as regular variables which are all separate.

$apple1 = new Apple();
$apple2 = new Apple();
$apple3 = new Apple();

Abstract Classes

An abstract class is an incomplete definition of something. In our example above, you will see that the “Fruit” class has the keyword “abstract” prepends the class definition. This means that you cannot create an instance of that particular class, and the only way to use it is by extending it.

The first line will result in an error because Fruit is abstract, but the second is OK because Orange is a full class:

$some_fruit = new Fruit(); // Errors
$some_orange = new Orange(); // OK!

Reserved variable name $this

Something you will use frequently in OOP is the self-referential pseudo-variable “$this”. $this points to it’s own instance in context, and you can use it to call member variables or functions. In our Orange class example above, we can see that the Prepare function calls to of it’s own methods – Peel() and SeparateChunks(). If these were public functions (you’ll find out what these are in a moment!), you would be able to call these separately in the same way as you call Prepare().

Basic Visibility – public, private

Visibility of methods and variables is also another important OOP principle. Before the function or variable name you are declaring (only in a class), you can define it’s visibility. Default visibility for a function is public, but I find it good practice to always explicitly declare visibility for clarity. In our Orange example, the only publically visible methods (i.e. outside the structure or definition of the class) are Prepare() and Serve(); Serve() is inherited from the parent class Fruit remember. Orange’s private methods (i.e. you cannot access these outside the class) are Peel(), GrateZest() and SeparateChunks().

The second line will result in an error because Peel is a private method, but the third is OK because Prepare() is a public method:

$orange = new Orange();
$orange->Peel(); // Error - Peel is not publically available
$orange->Prepare(); // OK - Prepare is publically available

There are a few more visibility operators, but these are the two basic ones you need to know about.

The Function (or Call) Stack

When calling functions, PHP maintains an internal list (or stack) of what is going on. You may have heard this term used in other programming languages, and most likely the term “Stack Dump”. I’ll briefly introduce the concept because I think it is useful to know how the engine works underneath.

Basically, at any one point in the execution of your script, you can do a “Stack Dump” which essentially is saying “output the call stack”. The call stack itself is a list of functions that have been called, and also indicates what the current function is.  To view the stack dump, you can use the debug_backtrace function, but I won’t go into detail about that for now.

In the Orange class, at the point of the line that echos “The zest of the orange has been saved for cooking”, the call stack will look something like this (and I’m excluding system call stack for simplicity!):

  • Prepare()
  • Peel()
  • GrateZest()

Basically, this means the Prepare function has been called, and inside that, the Peel() function has been called, and inside that the GrateZest() function has been called. When the GrateZest() has finished executing, the execute “returns” to the Peel() function and the call stack becomes:

  • Prepare()
  • Peel()

This concept of the stack is known has LIFO – or Last In, First Out – because the last item added to the stack is the first to be removed.

Constructors

A constructor is a PHP “magic” method. Magic methods are normally identified by the double underscore (_) before the function name. The constructor magic method is executed at the creation time of the class instance. This is how we make “You have created an Apple” appear. When the code:

$my_apple = new Apple();

is run, PHP magically executes the code within the __construct() function. You can provide extra arguments to the construct function, for example:

class SomeClass
{
  private $_value;
 
  public function __construct($a, $b)
  {
    $this->_value = $a + $b;
  }
 
  public function GetValue()
  {
    return $this->_value;
  }
}
 
$instance = new SomeClass(5, 10);
echo "The result is: " . $instance->GetValue();
// Output would be:
//   The result is: 15

Closing Words

There you have it – some basic OOP knowledge. If you’ve followed me to this point, then you’re doing really well. Jumping straight into OOP PHP isn’t the easiest way to start by any means, and means you have to learn some concepts of OOP as well as learning syntax, so it’s a bit of a head full to begin with. The aim of these tutorials is to start you thinking OOP at the very first instance, instead of thinking “I do it this way in a procedural script, how can I translate this into OOP?”, which may not be the most efficient way of doing things.

2 Responses to “PHP Basics – Part I: Hello Classy World”

  1. Links for 6th September 2010 | Velcro City Tourist Board says:

    [...] PHP Basics – Part I: Hello Classy World [...]

  2. James Titcumb » Blog Archive » PHP Basics – where next? says:

    [...] folks. Not sure if you’ve seen my recent behemoth posts (part 1 and part 2), and if you haven’t please check them out.  had intended to do a full on series [...]

Leave a Reply