Learn to Program with PHP - Part 1: Setup and Classes
Which Language to Learn
A good friend of mine asked me
“What programming language would you have someone learn who is interested in coding?”
Spoiler, “someone” was him.
At this point you might be saying one of two things
1. “Geez. That depends. I need to ask some questions.”
2. Or “Ugh. Backstory. Gross.” and if that’s you then skip ahead.
I asked him about his interests in programming, and what he wanted to build. I’d like to note right now that he’s not in college and works for a living. I also know that he’s not super invested in programming. He has a lot of different interests, and this interest is likely going to come second to many of the others.
So I’d like to make this easy for him so he can finish his project while also teaching him as many programming principles as possible.
By the end of the conversation, I was sitting on a list of Python, Java, or PHP.
His project would be best built with a web interface. They all have great frameworks, but because he has work experience that occasionally exposed him to PHP applications I figured this would be the easiest route for him.
Of course, there are some pits I’ve seen new PHP developers fall into often.
I’m here to make sure the right tools, frameworks, and programming principles are introduced.
This tutorial will assume you’re just starting your very first PHP app on a Mac computer.
It also assumes you’re comfortable opening the terminal.
Feel free to ride along!
Tools
First things first. You’re going to need the tools to develop a PHP application.
We are going to take the free route. Nothing here is going to require any money 🍞.
First, we need PHP. Now Mac’s come with PHP installed, but I’ve always been a fan of Homebrew as a software package manager. It will help us easily download some other key tools we will be using. There are some requirements before we can install that. One of them being the Xcode command line tools.
Install those with xcode-select --install
Once you’re done with that, go to the Homebrew website and copy the command to install it. Follow any directions given to you at the terminal.
Then we need to install PHP.
You can search brew packages with brew search package-name
We’re going to install the latest version of PHP (currently 8) with brew install php. Follow any additional prompts that brew might give you. You can see a successful install with php -v, which will give you the version.
There’s more configuration to do here, but we’ll come back to it later.
Now we need an editor. We are going to use VS Code. Install that from the official VS Code website.
VS Code is very lightweight out of the box. So we’re going to install some things.
Let’s install something that will help you be more efficient.
Hit CMD + Shift + P. This is called the Command Palette.
Type i and select Extensions: Install Extensions
First, search for PHP Intelephense
Install it. There isn’t anything else to do here.
Also. while you have that palette open, type code and select Shell Command: Install 'code' command in PATH. Open a new terminal window and you can cd to projects and open them with code . where the dot is the path to your project.
Baby Basics
First, you should cover the baby basics. Though it’s not always the best resource, w3schools has some easily digestible material. It should cover the basics of PHP in a very short amount of time.
Skim through these links and you should be able to make your way through the rest of this tutorial.
Start here.
https://www.w3schools.com/php/php_syntax.asp
Make your way through the PHP Arrays section (including the indexed, associative, multidimensional, and sorting sections).
https://www.w3schools.com/php/php_arrays.asp
I'll wait here.
Done? Awesome. Let’s actually do something.
Getting Started (for real)
Make a directory somewhere and create an index.php file in it. Then open it with your new code command.
mkdir -p ~/projects/first-app
cd ~/projects/first-app
touch index.php`
code .index.php
<?php
echo "Hello world";
?>
There are 2 ways to run this. In a browser or as a script at the command line.
Try running it as a script first.
php index.phpIn a script like this, you would want to use the new line character \n and others for formatting. Try adding that and another echo command below the first one. Don’t forget your semicolon at the end of each statement.
If you put it in the browser, all your formatting will need to be done with html. Switch new line characters for <br> tags.
To see it in the browser, spin up a server with php -S localhost:8888
Now go to localhost:8888 in your browser.
Nice! Let’s learn something new.
We use “Objects” to define everything in the real world. This can be really helpful when designing programs that deal with real-world problems. In PHP we can create blueprints of these objects. We call them classes.
Create a folder called Objects. Inside that folder, create a new file called Dog.php. By convention, classes are titlecased. Another example being “SmartDog”
Dog.php
<?php
class Dog {
public $numberOfLegs;
public $goodBoy;
public $vocab = [];
}We’ll start here. We first define what are called instance variables. The $ is how you declare a variable in PHP. You can make them private, public, or protected. They control access to the variables from other parts of your program. Don’t worry about it too much for now.
This is great, but it won’t work without what’s called a ‘constructor’. We have a magic function in PHP that looks like this.
Dog.php
<?php
class Dog {
public $numberOfLegs;
public $goodBoy;
public $vocab = [];
public function __construct() {
}
}This constructor function needs to be public because we do want to give other programs the ability to create new instances of this class.
Dog.php
<?php
class Dog {
public $numberOfLegs;
public $goodBoy;
public $vocab = [];
public function __construct($numberOfLegs, $goodBoy, $vocab) {
$this->numberOfLegs = $numberOfLegs;
$this->goodBoy = $goodBoy;
$this->vocab = $vocab;
}
}Here we are passing parameters for the instance variables we want to set. Then we use the special keyword variable $this which refers to the class itself.
So we first set the numberOfLegs for $this Dog equal to whatever we want. Then the same for goodBoy, and vocab.
Save your work and go back to index.php
Index.php
<?php
require "Objects/Dog.php";
$lucky = new Dog(4, true, ['bark', 'woof']);
?>
Here we can require our Dog class. The require keyword will force the program to fail if it can’t find the file.
Then we ‘instantiate’ or ‘new up’ an instance of ‘Dog’. You can see here how we pass our parameters. Then we assign it to the variable $lucky
We have a dog with 4 legs. It is a good boy. And it’s got a diverse vocabulary of ‘bark’ and ‘woof’.
So what do we want the Dog to do? I find it’s helpful to write out code in plain English before you implement it.
<?php
require "Objects/Dog.php";
$lucky = new Dog(4, true, ['bark', 'woof']);
$lucky->speak();
?>
We might want to write a method called speak.
A function within a class is often referred to as a method. If the function did not belong to an object, then it would be referred to as a function.
Obviously, this will fail if you run it though because the speak method does not exist. Let’s fix that
Dog.php
<?php
class Dog {
public $numberOfLegs;
public $goodBoy;
public $vocab = [];
public function __construct($numberOfLegs, $goodBoy, $vocab) {
$this->numberOfLegs = $numberOfLegs;
$this->goodBoy = $goodBoy;
$this->vocab = $vocab;
}
public function speak() {
if (sizeof($this->vocab) > 0) {
/* We create a random number.
We start at 0 because that's where arrays start.
We end with the size of the (vocab - 1) because sizeof
gives us the number as if we had counted starting
from 1.
If we have 2 items at space 0 and 1, and we want
to create a random number for index 0 through 1,
we can't go to 2 or we'll get an "IndexOutOfBoundsException"
*/
$r = rand(0, sizeof($this->vocab)-1);
// We select a random string from the vocabulary.
echo $this->vocab[$r];
} else {
// No vocab.
echo "...";
}
}
}Now go back and run index.php as a script or in the browser.
That’s it for this part. In Part 2, we’ll cover inheritance.
