BDI Logo

Introduction to PHP

Class 3

Let's Develop It

Let's get PHP running on your machine.

PCs: http://www.wampserver.com/en/download.php

Macs: http://www.mamp.info/en/downloads/index.html

Test: http://localhost/

Let's Develop It

Make your first page! Find your www directory. On Windows, the default is C:\wamp\www. On a Mac, it is \Applications\MAMP\htdocs\. Create a new folder, called gdi, and then create a file inside called index.php.

<!DOCTYPE html>
<html>
  <head>
    <title>Test Page</title>
  </head>
  <body>
    <p>
    <?php
    echo 'Hello World';
    ?>
    </p>
  </body>
</html>

Let's Develop It

If everything worked, you should see your new page at http://localhost/gdi

Include

Remeber DRY code (Don't Repeat Yourself)? One of the best ways to avoid repeating code is to use include. The include command will include all the code from another file inside the current file. This is a powerful way to use a common file for repeated site elements, like a header, footer, or sidebar.

Using Include

Let's say you have one file called vars.php, where you store all your common variables.

$color = 'green';
$fruit = 'apple';

If you include this file in another file, you can use those variables.

echo "A $color $fruit"; // Outputs A
include 'vars.php';
echo "A $color $fruit"; // Outputs A green apple

Let's Develop It

I have created a basic sample site, broken into a header, footer, and sidebar.

  • Download a copy and place all the files directly into your gdi folder
  • Go to http://localhost/gdi/sample.php to see the page
  • Using your text editor, look at the different pieces of the site. Try changing things and see what happens!

Loops

Kitten in ball

Photo credit: Courtney Patubo Kranzke cc

While loops

While will repeat the same code over and over until some condition is met.

$bottlesOfBeer = 99;
while ($bottlesOfBeer >= 1) {
  echo $bottlesOfBeer . ' bottles of beer on the wall <br />';
  $bottlesOfBeer = $bottlesOfBeer - 9;
}

Infinite Loops

Make sure something changes in the loop, or your loop will go on forever...

Spiral that goes on toward infinity

Photo credit: Samuel John cc

For loops

For loops are very similar, but you declare a counter in the statement.

//will count 1 to 10
for ($i = 1; $i <= 10; $i++) {
  echo $i;
}

Loops and logic

You can add other statements or logical operators inside the loops.

//Count from 1 to 50.
for ($i = 1; $i <= 50; $i++) {
  echo $i;
  //Says 'Buzz' after multiples of three
  if ($i%3 == 0) {
    echo ' Buzz';
  }
  //Says 'Bang' after multiples of five
  if ($i%5 == 0) {
    echo ' Bang';
  }
  echo '<br />'; //line break
}

Let's Develop It

Write a loop that gives you the 9's times table,
from 9 x 1 = 9 to 9 x 12 = 108.

Finish early? Try using a loop inside a loop to write all the times tables, from 1 to 12.

Arrays

Group of kittens

Photo credit: Jesus Solana cc

Arrays

Arrays are lists of values associated with a key. The key needs to be an integer or a string, the value can be any type.

$kittenColors = array(
  'Fluffy' => 'tabby',
  'Midnight' => 'black',
  'Admiral Snuggles' => 'white'
);

Using arrays

Once you have an array, you use a key to call a value.

$kittenColors = array(
  'Fluffy' => 'tabby',
  'Midnight' => 'black',
  'Admiral Snuggles' => 'white'
);
echo $kittenColors['Midnight']; //prints 'black'

Expanding arrays

Arrays don't have a fixed length; you can add and take away items.

$kittenColors = array(
  'Fluffy' => 'tabby',
  'Midnight' => 'black',
  'Admiral Snuggles' => 'white'
);

// This adds a new element to the array with key 'Monster'
$kittenColors['Monster'] = 'gray';

// This removes the element with the key 'Midnight'
unset($kittenColors['Midnight']);

Arrays without keys

If you don't specify a key, PHP will just automatically assign integers as keys, starting with zero.

$fruits = array("apple", "orange", "banana", "kiwi");
var_dump($fruits); //shows whole array
echo $fruits[1]; //will print orange

//You can add with no key as well
$fruits[] = 'mango';
var_dump($fruits);

Let's Develop It

Create an array of your friends and their favorite foods. Echo a few values onto your screen.

Foreach

Couple holding hands

Photo credit: John cc

Foreach loops

Foreach is a special type of loop that works with arrays.

$numberList = array(1, 2, 3, 4, 5);
foreach ($numberList as $value) {
  echo "$value times 2 equals " . ($value*2) . "
"; }

Arrays with keys

You can also use the key values in your foreach loop.

$kittenColors = array(
  'Fluffy' => 'tabby',
  'Midnight' => 'black',
  'Admiral Snuggles' => 'white',
);

foreach ($kittenColors as $name => $color) {
  echo "The kitten $name has $color fur.
"; }

Let's Develop It

Take your array of friends and write a foreach loop that echos "My friend NAME likes FOOD."

Objects

Collection of matches

Photo credit: Jirí Volejník cc

PHP is an object-oriented language

  • In the real world, important information often comes in collections. For example, a robot has attributes (material, color) and behaviors (beep, walk).
  • Objects allow us to represent these things in our code.
  • Objects are collections of related variables and functions.
  • Inside an object, variables are called properties (or attributes), and functions are called methods.

Declaring an object

In PHP, you declare an object using the keyword class

class cat {

}

You can create a new instance of this object using the keyword new

$myKitty = new cat();

Object properties

Variables associated with a variable are called properties. Properties can have starting values, or you can specify them when you create an instance of the object.

Properties must be be public, protected or private. For now, we'll use public.

class cat {
  public $isCute = true;
  public $furColor;
  public $name;
}

Using object properties

You can set and use object properties using the syntax $objectInstance->property

$myKitty = new cat();
$myKitty->furColor = "Calico";
$myKitty->name = "Caramel";
echo $myKitty->name;

Let's Develop It

  • Create a vehicle object to store information about a vehicle. It should have properties for vehicleType (e.g., car, truck, plane), color, and topSpeed.
  • Set at least one default value when you define your object.
  • Create at least two instances of your object.
  • Set and display some object properties.

Object constructors

Objects can also hold functions, called methods. A common method is a constructor. This is a simple function that makes it easy to set object properties when you make a new instance of the object.

class cat {
  public $isCute = true;
  public $furColor;
  public $name;

  public function __construct($furColor, $name) {
    $this->furColor = $furColor;
    $this->name = $name;
  }
}

Object constructors

Once we have a constructor, we can specify properties when we create a new instance

$myKitty = new cat("calico", "Caramel");
$neighborCat = new cat("gray", "Smoky");

Let's Develop It

  • Go back to your vehicle object. Add a constructor.
  • Use the constructor when you create an instance of the vehicle object.

Object methods

We can also add other methods to the class.

class cat {
  public $isCute = true;
  public $furColor;
  public $name;

  public function greet() {
    return "Hi, $this->name! You are a pretty $this->furColor cat.
"; } }

Using object methods

Calling a method is similar to a property, with the syntax $objectInstance->method(). For example

echo $myKitty->greet();
echo $neighborCat->greet();

Reference: Completed object code

class cat {
  public $isCute = true;
  public $furColor;
  public $name;

  public function __construct($furColor, $name) {
    $this->furColor = $furColor;
    $this->name = $name;
  }

  public function greet() {
    return "Hi, $this->name! You are a pretty $this->furColor cat.
"; } } $myKitty = new cat("calico", "Caramel"); $neighborCat = new cat("gray", "Smoky"); echo $myKitty->furColor . "
"; echo $myKitty->greet(); echo $neighborCat->greet();

Let's Develop It

  • Go back to your vehicle object. Add a method to say "This [vehicleType] is [color]".
  • Call that method.

You did it!

Fireworks

Photo credit: Mark W. cc

Resources

  • PHP Manual, the official PHP documentation. Check the comments; they are useful.
  • Code Academy, with interactive PHP lessons to help you review.