mirror of
https://github.com/restoreddev/phpapprentice.git
synced 2025-08-06 06:47:58 +02:00
Created initial site setup with hugo
This commit is contained in:
58
content/01-basics.md
Normal file
58
content/01-basics.md
Normal file
@@ -0,0 +1,58 @@
|
||||
+++
|
||||
title = "Basics"
|
||||
description = "Getting Started"
|
||||
tags = ["php", "basics"]
|
||||
slug = "basics"
|
||||
next = "variables.html"
|
||||
+++
|
||||
If you want to follow along by writing code, start by downloading a code editor. I recommend
|
||||
[Visual Studio Code](https://code.visualstudio.com/) or [Sublime Text](https://www.sublimetext.com/).
|
||||
Next, create a new file in your editor called `basics.php` and save it anywhere on your computer, like a folder
|
||||
in your documents called `phpapprentice`. Now, we can write some PHP.
|
||||
|
||||
All PHP files must start with a `<?php` tag unless it is for a html template.
|
||||
(We will learn about html templates later.)
|
||||
```php
|
||||
<?php
|
||||
|
||||
echo "Hello World!\n";
|
||||
```
|
||||
|
||||
There is a lot going on in the above code so let's work through it.
|
||||
|
||||
First, the echo keyword tells PHP to output some text.
|
||||
```php
|
||||
echo "I am some text\n";
|
||||
```
|
||||
|
||||
Second, PHP stores text in strings. To write a string, you surround letters with single or double quotes.
|
||||
Double quoted strings can hold special characters like `\n` which tells PHP to start a new line.
|
||||
```php
|
||||
echo "I am a string on a new line\n";
|
||||
```
|
||||
|
||||
Third, all lines of code in PHP must end in a semi-colon.
|
||||
```php
|
||||
echo "No semi-colon is a no-no\n";
|
||||
```
|
||||
|
||||
Using semi-colons means we can write multiple statements on one line.
|
||||
```php
|
||||
echo "PHP"; echo " Apprentice\n";
|
||||
```
|
||||
|
||||
To execute the code you have written, make sure you have [PHP installed](/installing-php.html).
|
||||
Then, open a terminal app, either Terminal on MacOS or Powershell on Windows. In the terminal,
|
||||
open the folder where you created the `basics.php` file using `cd`. For example, on Windows run `cd C:\%userprofile%\Documents\phpapprentice` and on Mac run `cd ~/Documents/phpapprentice`. Finally, you can execute the file by running `php basics.php`.
|
||||
|
||||
In your terminal, you should see:
|
||||
```bash
|
||||
Hello World!
|
||||
I am some text
|
||||
I am a string on a new line.
|
||||
No semi-colon is a no-no
|
||||
PHP Apprentice
|
||||
```
|
||||
|
||||
With any code in future chapters, I recommend writing a PHP file for it.
|
||||
It is a great way to get some practice with the language.
|
43
content/02-variables.md
Normal file
43
content/02-variables.md
Normal file
@@ -0,0 +1,43 @@
|
||||
The variable is the basic building block of any programming language.
|
||||
In PHP, all variables start with a dollar sign.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$greeting;
|
||||
```
|
||||
|
||||
To set data in a variable, you put an equals sign after it and some data.
|
||||
```php
|
||||
$greeting = 'Hello World!';
|
||||
```
|
||||
|
||||
Once you create a variable, you can use it again in other commands and functions.
|
||||
```php
|
||||
echo $greeting;
|
||||
```
|
||||
|
||||
After the dollar sign, a PHP variable must have an alphabetic character or underscore. Also, variables are case sensitive.
|
||||
```php
|
||||
$_var = 'I am a variable with an underscore!';
|
||||
$Var = 'I am a variable with a capital letter!';
|
||||
$var = 'I am a new variable';
|
||||
```
|
||||
|
||||
Variables can hold many different types of data, but there are four simple ones you can try now.
|
||||
An int is a number without a decimal place.
|
||||
A float is a number with a decimal place.
|
||||
A boolean can be two values: true or false.
|
||||
Last, there is a string: a collection of characters.
|
||||
```php
|
||||
$int = 1;
|
||||
$float = 100.10;
|
||||
$bool = true;
|
||||
$string = 'I am a string';
|
||||
```
|
||||
|
||||
In other programming languages, you have to write what type of data the variable will contain.
|
||||
PHP keeps it simple by allowing you to put any type of data in a variable, including already used variables.
|
||||
```php
|
||||
$number = 1;
|
||||
$number = 'one';
|
||||
```
|
40
content/03-arithmetic.md
Normal file
40
content/03-arithmetic.md
Normal file
@@ -0,0 +1,40 @@
|
||||
Now that we know how to create variables, let's look at doing some math.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$a = 1;
|
||||
$b = 2;
|
||||
```
|
||||
|
||||
To add two values, use the plus symbol.
|
||||
```php
|
||||
echo $a + $b;
|
||||
```
|
||||
|
||||
To subtract, use the minus symbol.
|
||||
```php
|
||||
echo $b - $a;
|
||||
```
|
||||
|
||||
To multiply two values, use an asterisk.
|
||||
```php
|
||||
echo $a * $b;
|
||||
```
|
||||
|
||||
To divide values, use a forward slash.
|
||||
```php
|
||||
echo $b / $a;
|
||||
```
|
||||
|
||||
PHP uses the percent symbol for calculating the modulus of two numbers.
|
||||
The modulus is calculated by dividing two numbers and returning the remainder of the result.
|
||||
In this example, the value of $mod will be 0.
|
||||
```php
|
||||
$mod = 10 % 5;
|
||||
```
|
||||
|
||||
You can also use double asterisks to calculate a number to the power of another number.
|
||||
The following statement will print 25.
|
||||
```php
|
||||
echo 5 ** 2;
|
||||
```
|
31
content/04-strings.md
Normal file
31
content/04-strings.md
Normal file
@@ -0,0 +1,31 @@
|
||||
As seen in the first chapter, a string is a group of characters created by
|
||||
surrounding text in single or double quotes.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$firstname = 'Joey';
|
||||
$lastname = "Johnson";
|
||||
```
|
||||
|
||||
A double quoted string can interpret special characters starting
|
||||
with a back slash to create formatting. The `\n` creates a newline
|
||||
between the names and after them.
|
||||
```php
|
||||
echo "Jacob\nJones\n";
|
||||
```
|
||||
|
||||
Double quoted strings can also embed variables in the text. This code
|
||||
outputs "Cindy Smith".
|
||||
```php
|
||||
$firstname = 'Cindy';
|
||||
echo "$firstname Smith\n";
|
||||
```
|
||||
|
||||
Another feature of strings is the ability to combine them together.
|
||||
To combine two strings, use the period character in between them.
|
||||
```php
|
||||
$firstname = 'Jenny';
|
||||
$lastname = 'Madison';
|
||||
$fullname = $firstname . $lastname;
|
||||
echo $fullname;
|
||||
```
|
56
content/05-comparisons.md
Normal file
56
content/05-comparisons.md
Normal file
@@ -0,0 +1,56 @@
|
||||
A boolean is a value that is always 0 or 1, yes or no, on or off.
|
||||
In PHP, a boolean is represented by the words true and false.
|
||||
While programming, you will often want to know if something is positive or negative.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$a = true;
|
||||
$b = false;
|
||||
```
|
||||
|
||||
There are many constructs and functions that will return a boolean.
|
||||
To start, let's look at comparisons.
|
||||
|
||||
Double equals checks if two values are equal.
|
||||
```php
|
||||
$one = 1;
|
||||
$two = 2;
|
||||
|
||||
$one == $two; // returns false
|
||||
```
|
||||
|
||||
An exclamation point and equal sign check if two values are not equal.
|
||||
```php
|
||||
$one != $two; // returns true
|
||||
```
|
||||
|
||||
You can use greater than and less than symbols to check for comparisons too.
|
||||
```php
|
||||
$one > $two; // returns false
|
||||
$one < $two; // returns true
|
||||
```
|
||||
|
||||
If you combine a greater than or less than symbol with an equal,
|
||||
it will check if the value is greater or less than or equal to another value.
|
||||
```php
|
||||
$one <= $two;
|
||||
$one >= $two;
|
||||
```
|
||||
You can also check that two values are equal and of the same type
|
||||
by using three equal signs.
|
||||
|
||||
The following comparisons return true.
|
||||
```php
|
||||
1 == 1;
|
||||
1 == '1';
|
||||
1 == true;
|
||||
1 == 1.0;
|
||||
1 === 1;
|
||||
```
|
||||
|
||||
These return false.
|
||||
```php
|
||||
1 === '1';
|
||||
1 === true;
|
||||
1 === 1.0;
|
||||
```
|
34
content/06-boolean-logic.md
Normal file
34
content/06-boolean-logic.md
Normal file
@@ -0,0 +1,34 @@
|
||||
Boolean logic is used to combine booleans to return another boolean.
|
||||
|
||||
Using double ampersands tells PHP to check if both values are true.
|
||||
If so, it will return true. If not, it will return false.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$a = true;
|
||||
$b = true;
|
||||
$c = false;
|
||||
|
||||
$a && $b; // returns true
|
||||
$a && $c; // returns false
|
||||
```
|
||||
|
||||
Using two pipe characters checks if either value is true.
|
||||
Then, it will return true. If both values are false, then PHP
|
||||
returns false.
|
||||
```php
|
||||
$a = true;
|
||||
$b = false;
|
||||
$c = false;
|
||||
$d = true;
|
||||
|
||||
$a || $b; // returns true
|
||||
$b || $c; // returns false
|
||||
$a || $d; // returns true
|
||||
```
|
||||
|
||||
Using an exclamation point returns the opposite value.
|
||||
```php
|
||||
$d = true;
|
||||
echo !$d; // outputs false
|
||||
```
|
83
content/07-conditionals.md
Normal file
83
content/07-conditionals.md
Normal file
@@ -0,0 +1,83 @@
|
||||
When writing code, there will be times when you need to perform actions only under certain circumstances.
|
||||
There are several ways to control execution in PHP.
|
||||
We will start with an if statement.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$animal = 'cow';
|
||||
if ($animal == 'cow') {
|
||||
echo "Moooooo.....\n";
|
||||
}
|
||||
```
|
||||
|
||||
All conditionals check to see if a statement evaluates to true or false.
|
||||
In the case above, since `$animal` equals 'cow', the statement returns true and the contents of the if statement are executed.
|
||||
|
||||
An if statement can have multiple conditions chained together.
|
||||
If the first if statement returns false, then PHP will check each `elseif`.
|
||||
If none of the checks return true, then the `else` block will be executed.
|
||||
```php
|
||||
$animal = 'bird';
|
||||
if ($animal == 'dog') {
|
||||
echo "Woof! 🐶\n";
|
||||
} elseif ($animal == 'cat') {
|
||||
echo "Meow!? 🐱\n";
|
||||
} elseif ($animal == 'bird') {
|
||||
echo "Chirp! 🐦\n";
|
||||
} else {
|
||||
echo "I am not a dog, cat or bird\n";
|
||||
}
|
||||
```
|
||||
|
||||
An alternative to the if statement is the switch.
|
||||
A switch statement has multiple cases to check if the value in parentheses equals something.
|
||||
In this statement, since `$food` equals 'apples', the switch will echo "Eating an apple".
|
||||
The default case will be run if no other case evaluates to true, like an else statement.
|
||||
```php
|
||||
$food = 'apples';
|
||||
switch ($food) {
|
||||
case 'apples':
|
||||
echo "Eating an apple\n";
|
||||
break;
|
||||
case 'oranges':
|
||||
echo "Eating an orange\n";
|
||||
break;
|
||||
case 'peaches':
|
||||
echo "Eating a peach\n";
|
||||
break;
|
||||
default:
|
||||
echo "No food, I am hungry\n";
|
||||
}
|
||||
```
|
||||
|
||||
Breaks are a special keyword that tell PHP to stop execution once a case passes.
|
||||
If you do not use a break, PHP will continue to execute all following cases.
|
||||
In this switch, both "Drinking water" and "Drinking tea" will be executed since there is no break in the 'water' case.
|
||||
```php
|
||||
$drink = 'water';
|
||||
switch ($drink) {
|
||||
case 'water':
|
||||
echo "Drinking water\n";
|
||||
case 'tea':
|
||||
echo "Drinking tea\n";
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
PHP also supports single line conditionals called a ternary.
|
||||
In a ternary, the condition is followed by a question mark before the value that should be returned if the condition is true and then another colon and a value to return if the condition is false.
|
||||
```php
|
||||
$language = 'english';
|
||||
echo $language == 'spanish' ? "hola\n" : "hello\n";
|
||||
```
|
||||
|
||||
Lastly, there is another form of a ternary that checks if a value is set and then returns the value to the right of the two question marks if the value is null.
|
||||
```php
|
||||
echo $IDoNotExist ?? "Variable not set\n";
|
||||
```
|
||||
|
||||
You can also chain multiple checks in a row.
|
||||
```php
|
||||
$IExist = "Variable exists\n";
|
||||
echo $IDoNotExist ?? $IExist ?? "Neither variable is set\n";
|
||||
```
|
69
content/08-loops.md
Normal file
69
content/08-loops.md
Normal file
@@ -0,0 +1,69 @@
|
||||
A loop tells PHP to run a block of code more than once.
|
||||
A classic loop is a while loop.
|
||||
A `while` loop will continue to run the block of code as long as the value in parentheses is true.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$num = 5;
|
||||
while ($num > 0) {
|
||||
echo "While loop $num\n";
|
||||
--$num;
|
||||
}
|
||||
```
|
||||
|
||||
A `do while` loop is similar to a `while` loop except it always runs at least
|
||||
one iteration. In a classic `while` loop, no iterations may be executed if
|
||||
the value in parentheses is false. In a `do while`, the boolean check
|
||||
is not done until after the execution of an iteration.
|
||||
```php
|
||||
$num = 0;
|
||||
do {
|
||||
echo "Do while $num\n";
|
||||
++$num;
|
||||
} while ($num < 5);
|
||||
```
|
||||
|
||||
`for` loops allow you to create a more concise while loop.
|
||||
Inside the parentheses, the left section creates a variable before the loop
|
||||
starts, the middle section is the check that is done at the beginning of each loop
|
||||
and the third section is executed after each loop.
|
||||
```php
|
||||
for ($i = 0; $i < 10; $i++) {
|
||||
echo "For loop $i\n";
|
||||
}
|
||||
```
|
||||
|
||||
A `foreach` loop allows you to easily loop over an array.
|
||||
An array is a list of data stored together.
|
||||
The `as` keyword lets you assign a variable to the value
|
||||
in the array for the current iteration of the loop.
|
||||
```php
|
||||
$set = [1, 2, 3, 4, 5];
|
||||
foreach ($set as $num) {
|
||||
echo "Array value $num\n";
|
||||
}
|
||||
```
|
||||
|
||||
In loops, you can use the keyword `break` to stop the loop execution
|
||||
no matter how many more iterations should run.
|
||||
```php
|
||||
$values = ['one', 'two', 'three'];
|
||||
foreach ($values as $value) {
|
||||
if ($value === 'two') {
|
||||
break;
|
||||
}
|
||||
echo "Break $value\n";
|
||||
}
|
||||
```
|
||||
|
||||
The `continue` keyword stops executing the current loop iteration,
|
||||
but then allows the loop to continue with other iterations.
|
||||
```php
|
||||
$values = ['one', 'skip', 'three'];
|
||||
foreach ($values as $value) {
|
||||
if ($value === 'skip') {
|
||||
continue;
|
||||
}
|
||||
echo "Continue $value\n";
|
||||
}
|
||||
```
|
38
content/09-arrays.md
Normal file
38
content/09-arrays.md
Normal file
@@ -0,0 +1,38 @@
|
||||
In PHP, arrays are used to store a list of items in a single variable.
|
||||
There are two ways to create an array.
|
||||
|
||||
First, you can use the `array` construct to pass in values separated by commas
|
||||
and it will return an array.
|
||||
```php
|
||||
<?php
|
||||
|
||||
$taskList = array('grocery store', 'change car oil');
|
||||
```
|
||||
|
||||
Second, you can surround the list in square brackets.
|
||||
This style is the most common and recommended form
|
||||
of creating an array.
|
||||
```php
|
||||
$groceryList = ['bread', 'milk', 'eggs'];
|
||||
```
|
||||
|
||||
PHP will automatically assign index keys for each value in an array
|
||||
starting with 0. So, to access a value in an array you will
|
||||
pass the key number into brackets after the variable name.
|
||||
```php
|
||||
echo $groceryList[0] . "\n";
|
||||
echo $groceryList[1] . "\n";
|
||||
```
|
||||
|
||||
You can also assign keys in an array using numbers or strings.
|
||||
It is very common to create an array with string keys. The feature
|
||||
is called an associative array or a map.
|
||||
```php
|
||||
$car = ['make' => 'Toyota', 'model' => 'Camry'];
|
||||
```
|
||||
|
||||
To access the value in an associative array, just use the string key in brackets
|
||||
after the variable name.
|
||||
```php
|
||||
echo $car['model'] . "\n";
|
||||
```
|
62
content/10-functions.md
Normal file
62
content/10-functions.md
Normal file
@@ -0,0 +1,62 @@
|
||||
A function allows you to store code under a name and then execute
|
||||
that code later.
|
||||
|
||||
A function always starts with the
|
||||
function keyword followed by the name with parentheses and then
|
||||
opening and closing curly braces around the code.
|
||||
```php
|
||||
<?php
|
||||
|
||||
function hello_world() {
|
||||
echo "hello world\n";
|
||||
}
|
||||
```
|
||||
|
||||
To call the function, use the function name with parentheses.
|
||||
```php
|
||||
hello_world();
|
||||
```
|
||||
|
||||
You can set up values to be passed into a function.
|
||||
To do so, write variables in between the function parentheses.
|
||||
Each one should be separated by a comma.
|
||||
```php
|
||||
function greet($firstname, $lastname) {
|
||||
echo "hello $firstname $lastname\n";
|
||||
}
|
||||
```
|
||||
|
||||
Then, you can pass in values when calling a function. In the greet function,
|
||||
'John' is assigned to `$firstname` and 'Smith' is assigned to
|
||||
`$lastname`.
|
||||
```php
|
||||
greet('John', 'Smith');
|
||||
```
|
||||
|
||||
You can also return a value from a function. You can only
|
||||
return a single value from a function.
|
||||
```php
|
||||
function capitalize($value) {
|
||||
return mb_strtoupper($value);
|
||||
}
|
||||
```
|
||||
|
||||
When calling a function, it will output the return value which
|
||||
you can load into a variable.
|
||||
```php
|
||||
$animal = capitalize('dog');
|
||||
echo "$animal\n";
|
||||
```
|
||||
|
||||
You can also create nameless functions called closures. Closures can be
|
||||
stored in variables or passed into other functions.
|
||||
```php
|
||||
$sum = function ($a, $b) {
|
||||
return $a + $b;
|
||||
};
|
||||
```
|
||||
|
||||
You can execute a closure by putting parentheses after the variable that contains the closure.
|
||||
```php
|
||||
echo $sum(1, 2) . "\n";
|
||||
```
|
63
content/11-classes.md
Normal file
63
content/11-classes.md
Normal file
@@ -0,0 +1,63 @@
|
||||
Classes allow you to define your own data types. All classes start with the
|
||||
class keyword followed by the name of the class and opening and closing curly braces.
|
||||
```php
|
||||
<?php
|
||||
|
||||
class Car
|
||||
{
|
||||
}
|
||||
```
|
||||
|
||||
To create an instance of a class, you use the `new` keyword in front of the class name
|
||||
with parentheses.
|
||||
```php
|
||||
$car = new Car();
|
||||
```
|
||||
|
||||
A class can define attributes and methods. An attribute is a piece of data
|
||||
stored on the class instance. You can define an attribute by adding the
|
||||
word `public` and a variable name inside the class definition.
|
||||
```php
|
||||
class Bicycle
|
||||
{
|
||||
public $color;
|
||||
}
|
||||
```
|
||||
|
||||
Then, when you create an instance of the class, you can set and use
|
||||
the attribute on the instance using `->`.
|
||||
```php
|
||||
$bike = new Bicycle();
|
||||
$bike->color = 'Blue';
|
||||
echo $bike->color . "\n";
|
||||
```
|
||||
|
||||
An instance of a class is called an object. Congratulations!
|
||||
You are now performing object-oriented development.
|
||||
```php
|
||||
$redBike = new Bicycle();
|
||||
$redBike->color = 'Red';
|
||||
echo $redBike->color . " Bike Object\n";
|
||||
```
|
||||
|
||||
A method is a function attached to the class. You can add a method
|
||||
to a class by using the `public` keyword followed by the function. A method
|
||||
can access the attributes and methods of an object instance using the `$this` variable.
|
||||
```php
|
||||
class Tricycle
|
||||
{
|
||||
public $color;
|
||||
|
||||
public function echoColor()
|
||||
{
|
||||
echo $this->color . "\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can execute a method on an object using the same `->` arrow characters with parentheses after the method name.
|
||||
```php
|
||||
$bike = new Tricycle();
|
||||
$bike->color = 'Red';
|
||||
$bike->echoColor();
|
||||
```
|
78
content/12-classes-inheritance.md
Normal file
78
content/12-classes-inheritance.md
Normal file
@@ -0,0 +1,78 @@
|
||||
In PHP, a class can extend another class, inheriting the parent class'
|
||||
properties and methods. To make a class a child of another, use the `extends`
|
||||
keyword after the class name.
|
||||
```php
|
||||
<?php
|
||||
|
||||
class Vehicle
|
||||
{
|
||||
public function drive()
|
||||
{
|
||||
echo "driving...\n";
|
||||
}
|
||||
}
|
||||
|
||||
class Truck extends Vehicle {}
|
||||
```
|
||||
|
||||
Using the `drive` method on the `Truck` class does not cause an error because `Truck` extends `Vehicle`.
|
||||
```php
|
||||
$truck = new Truck();
|
||||
$truck->drive();
|
||||
```
|
||||
|
||||
Even though the child class inherits a parent class' properties and methods,
|
||||
the child can still override the parent.
|
||||
```php
|
||||
class Tractor extends Vehicle
|
||||
{
|
||||
public function drive()
|
||||
{
|
||||
echo "driving slowly...\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The drive function now outputs "driving slowly..." instead of "driving...".
|
||||
```php
|
||||
$tractor = new Tractor();
|
||||
$tractor->drive();
|
||||
```
|
||||
|
||||
A class can use a parent's property or method from the `$this` variable.
|
||||
```php
|
||||
class Motorcycle extends Vehicle
|
||||
{
|
||||
public function pushPedal()
|
||||
{
|
||||
$this->drive();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `pushPedal` method outputs "driving...".
|
||||
```php
|
||||
$cycle = new Motorcycle();
|
||||
$cycle->pushPedal();
|
||||
```
|
||||
|
||||
If you override a parent's property or method, the `$this` variable will refer to the child's
|
||||
implementation of the property or method. To call the parent's property or method explicity,
|
||||
use the `parent` keyword.
|
||||
```php
|
||||
class Racecar extends Vehicle
|
||||
{
|
||||
public function drive()
|
||||
{
|
||||
parent::drive();
|
||||
|
||||
echo "driving even faster...\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `drive` method on `Racecar` now outputs "driving..." and "driving even faster...".
|
||||
```php
|
||||
$racecar = new Racecar();
|
||||
$racecar->drive();
|
||||
```
|
70
content/13-classes-visibility.md
Normal file
70
content/13-classes-visibility.md
Normal file
@@ -0,0 +1,70 @@
|
||||
In the last chapter, we defined properties and methods on the class using the public keyword.
|
||||
You can also define them using the `protected` and `private` keywords.
|
||||
Both keywords prevent the properties and functions from being accessible outside the object.
|
||||
Only the object itself can use each.
|
||||
```php
|
||||
<?php
|
||||
|
||||
class Phone
|
||||
{
|
||||
private $number;
|
||||
|
||||
public function setNumber($number)
|
||||
{
|
||||
$this->number = $number;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We cannot set the number using `$phone->number = '123-456-7890'`.
|
||||
Instead, we can use the public method.
|
||||
```php
|
||||
$phone = new Phone();
|
||||
$phone->setNumber('123-456-7890');
|
||||
```
|
||||
|
||||
Making an attribute or function private, gives you more control over the data in the object.
|
||||
For example, we could prevent a number being set if it starts with a 7.
|
||||
```php
|
||||
class Phone2
|
||||
{
|
||||
private $number;
|
||||
|
||||
public function setNumber($number)
|
||||
{
|
||||
if (substr($number, 0, 1) !== '7') {
|
||||
$this->number = $number;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `protected` and `private` keywords work a little differently.
|
||||
They both prevent functions and properties from being accessed outside an object.
|
||||
However, a method or property marked `protected` can still be accessed by a child class.
|
||||
```php
|
||||
class Phone3
|
||||
{
|
||||
private $number;
|
||||
|
||||
protected $caller;
|
||||
|
||||
public function setNumber($number)
|
||||
{
|
||||
$this->number = $number;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In class `Smartphone`, the `caller` property is accessible because the parent class
|
||||
has it marked as `protected`. However, `Smartphone` cannot access the `number` property
|
||||
because it is still listed as private.
|
||||
```php
|
||||
class Smartphone extends Phone3
|
||||
{
|
||||
public function setCaller($caller)
|
||||
{
|
||||
$this->caller = $caller;
|
||||
}
|
||||
}
|
||||
```
|
60
content/14-classes-constructor.md
Normal file
60
content/14-classes-constructor.md
Normal file
@@ -0,0 +1,60 @@
|
||||
Whenever you create an object in PHP, you put parentheses after the class name.
|
||||
In the previous examples, we always left the parentheses empty.
|
||||
```php
|
||||
<?php
|
||||
|
||||
class Hat
|
||||
{
|
||||
public $color;
|
||||
|
||||
public function setColor($color)
|
||||
{
|
||||
$this->color = $color;
|
||||
}
|
||||
}
|
||||
|
||||
$hat = new Hat();
|
||||
```
|
||||
|
||||
However, you can actually pass data into the parentheses like a function.
|
||||
The data will be passed to a special function on the class called a constructor.
|
||||
```php
|
||||
class Ballcap
|
||||
{
|
||||
public $color;
|
||||
|
||||
public function __construct($color)
|
||||
{
|
||||
$this->color = $color;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A constructor is not required, but can make creating a new object easier.
|
||||
They are usually used to define the initial value of a property.
|
||||
Instead of writing:
|
||||
```php
|
||||
$hat = new Hat();
|
||||
$hat->setColor('Red');
|
||||
```
|
||||
|
||||
You can write:
|
||||
```php
|
||||
$ballcap = new Ballcap('Blue');
|
||||
```
|
||||
|
||||
Constructors do not return values because the return value is always a new object.
|
||||
```php
|
||||
class Tophat
|
||||
{
|
||||
public function __construct($color)
|
||||
{
|
||||
return $color;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`$tophat` now holds an instance of `Tophat`, not the string "Grey".
|
||||
```php
|
||||
$tophat = new Tophat('Grey');
|
||||
```
|
81
content/15-static.md
Normal file
81
content/15-static.md
Normal file
@@ -0,0 +1,81 @@
|
||||
When writing a class, all of the properties and methods are being defined for the object
|
||||
that will be created from the class.
|
||||
```php
|
||||
<?php
|
||||
|
||||
class House
|
||||
{
|
||||
public $color;
|
||||
|
||||
public function __construct($color)
|
||||
{
|
||||
$this->color = $color;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Like building a house, a class is a blueprint that
|
||||
defines what the house can do and the object is the house itself that can actually
|
||||
perform the actions defined in the blueprint.
|
||||
```php
|
||||
$house = new House('Green');
|
||||
```
|
||||
|
||||
However, what if you want the blueprint to have properties and methods?
|
||||
That is when you use the `static` keyword. In this class, we will define a default color
|
||||
on the class itself and then use it when creating a new object.
|
||||
```php
|
||||
class Skyscraper
|
||||
{
|
||||
private static $popularColor;
|
||||
public $color;
|
||||
|
||||
public static function setDefaultColor($color)
|
||||
{
|
||||
self::$popularColor = $color;
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->color = self::$popularColor;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can access static methods and properties using double colons on `self` inside the object
|
||||
or on the class name outside of the object. Static methods and properties can only access
|
||||
other static methods and properties.
|
||||
```php
|
||||
Skyscraper::setDefaultColor('Grey');
|
||||
$skyscraper = new Skyscraper();
|
||||
echo $skyscraper->color . "\n";
|
||||
```
|
||||
|
||||
Often, you will see static constructors in PHP.
|
||||
A static constructor creates a new instance of an object. Why would do that when you can just use "new Class" to create
|
||||
the object? A common reason is to make the code more readable.
|
||||
```php
|
||||
class TinyHouse
|
||||
{
|
||||
private $color;
|
||||
private $wheels;
|
||||
private $trailer;
|
||||
|
||||
public static function build($color, $wheels, $trailer)
|
||||
{
|
||||
return new self($color, $wheels, $trailer);
|
||||
}
|
||||
|
||||
public function __construct($color, $wheels, $trailer)
|
||||
{
|
||||
$this->color = $color;
|
||||
$this->wheels = $wheels;
|
||||
$this->trailer = $trailer;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Using `build` can make more sense than `new`, but it is ultimately a personal preference.
|
||||
```php
|
||||
$house = TinyHouse::build('Blue', 4, true);
|
||||
```
|
62
content/16-interfaces.md
Normal file
62
content/16-interfaces.md
Normal file
@@ -0,0 +1,62 @@
|
||||
The word `interface` is a confusing term because it is used for so many different concepts.
|
||||
Most often, we use it to describe the appearance of an app and how a user interacts with it.
|
||||
However, in PHP, an interface is a special construct that acts as a contract for classes.
|
||||
An interface defines what methods a class should have.
|
||||
```php
|
||||
<?php
|
||||
|
||||
interface Chair
|
||||
{
|
||||
public function setColor($color);
|
||||
public function setLegs($number);
|
||||
}
|
||||
```
|
||||
|
||||
To use an interface with a class, you use the `implements` keyword after the class name.
|
||||
Now, the `Recliner` class must have a `setColor` method and a `setLegs` method.
|
||||
If you do not create the required methods on the class, PHP will throw an error.
|
||||
```php
|
||||
class Recliner implements Chair
|
||||
{
|
||||
private $color;
|
||||
private $legs;
|
||||
|
||||
public function setColor($color)
|
||||
{
|
||||
$this->color = $color;
|
||||
}
|
||||
|
||||
public function setLegs($number)
|
||||
{
|
||||
$this->legs = $number;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Interfaces are helpful when you are using code created by someone else.
|
||||
For example, another developer may have created code that manages online payments, but they want to give you
|
||||
the ability to create your own payment class that works with their code. In that case, the developer
|
||||
creates an interface with all the required methods they need to charge a payment. The interface
|
||||
becomes a contract between your code and the other developer's code to work a certain way.
|
||||
```php
|
||||
interface Payment
|
||||
{
|
||||
public function charge($amount);
|
||||
}
|
||||
|
||||
class CreditCard implements Payment
|
||||
{
|
||||
public function charge($amount)
|
||||
{
|
||||
// contacts a credit card payment provider...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Since `CreditCard` implements `Payment`, a developer can check that it implements `Payment` and then use the `charge` method knowing the function exists on the class.
|
||||
```php
|
||||
$creditCard = new CreditCard();
|
||||
if ($creditCard instanceof Payment) {
|
||||
$creditCard->charge(25);
|
||||
}
|
||||
```
|
58
content/17-abstract.md
Normal file
58
content/17-abstract.md
Normal file
@@ -0,0 +1,58 @@
|
||||
Abstract classes are similar to interfaces in that they define methods that a sub-class must implement.
|
||||
However, an abstract class can also have normal methods. To create an abstract class, use the `abstract`
|
||||
keyword followed by `class` and the name of the class.
|
||||
```php
|
||||
<?php
|
||||
|
||||
abstract class CellPhone
|
||||
{
|
||||
abstract public function unlock();
|
||||
|
||||
public function turnOn()
|
||||
{
|
||||
echo "Holding power button...\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To use an abstract class, you create another class that extends it and create any methods that were marked as abstract.
|
||||
A class can only extend one abstract class and the child class has to implement all abstract methods.
|
||||
```php
|
||||
class iPhone extends CellPhone
|
||||
{
|
||||
public function unlock()
|
||||
{
|
||||
echo "Touching fingerprint reader...\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this example, we use an abstract class to create the behavior for turning on a cell phone and then
|
||||
force the child classes to implement how to unlock the phone. We have clearly defined what a cell phone
|
||||
performs and we have limited code duplication.
|
||||
```php
|
||||
class Android extends CellPhone
|
||||
{
|
||||
public function unlock()
|
||||
{
|
||||
echo "Typing passcode...\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Our iPhone and Android classes can now both use the `turnOn` method and the `unlock` method.
|
||||
```php
|
||||
$iPhone = new iPhone();
|
||||
$iPhone->turnOn();
|
||||
$iPhone->unlock();
|
||||
|
||||
$android = new Android();
|
||||
$android->turnOn();
|
||||
$android->unlock();
|
||||
```
|
||||
|
||||
You cannot create an instance of an abstract class. PHP would not know how to use the abstract methods
|
||||
so when you try to create an abstract instance you will get an error.
|
||||
```php
|
||||
$cellPhone = new CellPhone(); // causes an error
|
||||
```
|
74
content/18-exceptions.md
Normal file
74
content/18-exceptions.md
Normal file
@@ -0,0 +1,74 @@
|
||||
Sometimes things go wrong when someone uses your code. How do we handle this situation?
|
||||
PHP has Exceptions to define errors and the ability to `throw` them to stop code
|
||||
execution and tell the user of your code that something is wrong.
|
||||
```php
|
||||
<?php
|
||||
|
||||
class Processor
|
||||
{
|
||||
public function charge($creditCard)
|
||||
{
|
||||
if (strlen($creditCard->getNumber()) !== 16) {
|
||||
throw new Exception('Credit card is not right');
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this case, if someone tried to use the `Processor` class
|
||||
to charge a credit card number that is not 16 characters long, an
|
||||
`Exception` will be thrown which stops the rest of the code from running.
|
||||
```php
|
||||
$processor = new Processor();
|
||||
$processor->charge('1234');
|
||||
```
|
||||
|
||||
A developer who wants to prevent an exception from stopping code execution
|
||||
can catch the exception and use it for logging or display the error to a user.
|
||||
|
||||
Just wrap the code that might throw an exception with the keyword `try` and braces
|
||||
followed by `catch`, the exception type in parentheses and more braces.
|
||||
```php
|
||||
try {
|
||||
$processor->charge('1234');
|
||||
} catch (Exception $e) {
|
||||
echo $e->getMessage() . "\n";
|
||||
}
|
||||
```
|
||||
|
||||
You can make your own custom exceptions as well. They are just classes
|
||||
that extend the `Exception` class.
|
||||
```php
|
||||
class MyCustomException extends Exception {}
|
||||
```
|
||||
|
||||
Then, you can try to catch your exception instead of the base exception.
|
||||
```php
|
||||
try {
|
||||
throw new MyCustomException('I am a custom exception');
|
||||
} catch (MyCustomException $e) {
|
||||
echo "Caught MyCustomException\n";
|
||||
}
|
||||
```
|
||||
|
||||
Since all exceptions inherit from `Exception`, catching
|
||||
`Exception` will catch any and all exceptions that might be thrown.
|
||||
```php
|
||||
try {
|
||||
throw new MyCustomException('I inherit from Exception');
|
||||
} catch (Exception $e) {
|
||||
echo "Still caught MyCustomException\n";
|
||||
}
|
||||
```
|
||||
|
||||
You can also create multiple catch blocks to handle different types of exceptions in
|
||||
one try-catch.
|
||||
```php
|
||||
try {
|
||||
throw new MyCustomException('I am being thrown again');
|
||||
} catch (MyCustomException $e) {
|
||||
echo "MyCustomException was caught\n";
|
||||
} catch (Exception $e) {
|
||||
echo "Just in case a different exception is thrown\n";
|
||||
}
|
||||
```
|
0
content/_index.md
Normal file
0
content/_index.md
Normal file
67
content/web/01-http.md
Normal file
67
content/web/01-http.md
Normal file
@@ -0,0 +1,67 @@
|
||||
HTTP stands for Hypertext Transfer Protocol. It is a standard for how requests and responses should be formatted for
|
||||
a server and a web browser. When you open a link in your web browser, you are sending a HTTP request to a server and it
|
||||
is responding with a HTTP response. The browser then takes the response, parses it and displays it to the user.
|
||||
|
||||
Let us look at a HTTP request for PHP Apprentice. This is the request sent to the server from Firefox:
|
||||
```http
|
||||
GET /basics.html HTTP/2.0
|
||||
Host: phpapprentice.com
|
||||
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0
|
||||
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
|
||||
Accept-Language: en-US,en;q=0.5
|
||||
Accept-Encoding: gzip, deflate, br
|
||||
Connection: keep-alive
|
||||
Upgrade-Insecure-Requests: 1
|
||||
Pragma: no-cache
|
||||
Cache-Control: no-cache
|
||||
```
|
||||
The first line of the request tells us three things. First, the method of the request. A `GET` request tells the server
|
||||
that the browser just wants to download whatever is stored at the link. The second value `/basics.html` determines
|
||||
what should be loaded from `phpapprentice.com`. Finally, the third value tells the server what type of HTTP request it is.
|
||||
|
||||
All of the lines below the top line are key/value pairs called headers. They give the server different pieces of information
|
||||
about the client and the request to the server. For example, `Host` tells the server what website the browser is
|
||||
trying to access.
|
||||
|
||||
In response to the client's HTTP request, the server will respond with a HTTP response. Here is the response for the above request:
|
||||
```http
|
||||
HTTP/2.0 200 OK
|
||||
server: GitHub.com
|
||||
content-type: text/html; charset=utf-8
|
||||
last-modified: Sun, 13 Jan 2019 22:57:50 GMT
|
||||
etag: W/"5c3bc26e-15a0"
|
||||
access-control-allow-origin: *
|
||||
expires: Mon, 18 Feb 2019 02:38:31 GMT
|
||||
cache-control: max-age=600
|
||||
content-encoding: gzip
|
||||
x-github-request-id: 8596:461C:46C99E:5BB366:5C6A184F
|
||||
accept-ranges: bytes
|
||||
date: Mon, 18 Feb 2019 03:06:02 GMT
|
||||
via: 1.1 varnish
|
||||
age: 52
|
||||
x-served-by: cache-fty21342-FTY
|
||||
x-cache: HIT
|
||||
x-cache-hits: 2
|
||||
x-timer: S1550459163.720652,VS0,VE0
|
||||
vary: Accept-Encoding
|
||||
x-fastly-request-id: 00f0eec6f3037e428b8fc86742fe0f9965501a51
|
||||
content-length: 2084
|
||||
|
||||
```
|
||||
|
||||
The top line of the response is in two parts, similar to a request.
|
||||
The first part `HTTP/2.0` indicates the connection type, like the client.
|
||||
The second part `200 OK` is the response code. `200` indicates a successful response.
|
||||
There are many different response codes, the most famous being `404 Not Found`.
|
||||
|
||||
A response will have headers as well, but they are to give the client information about the response. As you can see,
|
||||
the `Content-Type` is set to `text/html`, which tells the client how to render the content of the response.
|
||||
|
||||
Notice that below the list of response headers, there is also the content of the response. In this case, it is just HTML
|
||||
which the browser can you use to display the page.
|
||||
|
||||
HTTP requests and responses are the core of web communication. Next, we will look at a request type other than `GET`.
|
||||
Notice that below the list of response headers, there is also the content of the response. In this case, it is just HTML
|
||||
which the browser can you use to display the page.
|
||||
|
||||
HTTP requests and responses are the core of web communication. Next, we will look at a request type other than `GET`.
|
34
content/web/02-http-post.md
Normal file
34
content/web/02-http-post.md
Normal file
@@ -0,0 +1,34 @@
|
||||
HTTP uses multiple different request types for indicating actions that should be performed on the server. The most common ones
|
||||
you will use are:
|
||||
- GET -> Retrieve a resource
|
||||
- POST -> Create a new resource
|
||||
- PUT -> Replace an entire resource
|
||||
- PATCH -> Update attributes of a resource
|
||||
- DELETE -> Delete a resource
|
||||
|
||||
We have already seen a GET request. The next most common request type is POST. A POST request is structured the same as a GET request, however, it will contain data in the request body:
|
||||
```http
|
||||
POST /login.php HTTP/1.1
|
||||
Host: localhost:8080
|
||||
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0
|
||||
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
|
||||
Accept-Language: en-US,en;q=0.5
|
||||
Accept-Encoding: gzip, deflate
|
||||
Referer: http://localhost:8080/login.php
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
Content-Length: 30
|
||||
Connection: keep-alive
|
||||
Upgrade-Insecure-Requests: 1
|
||||
Pragma: no-cache
|
||||
Cache-Control: no-cache
|
||||
|
||||
username=php&password=password
|
||||
```
|
||||
The above request is an example login request created by Firefox. You can see in the first line that POST is used to declare the request type.
|
||||
At the bottom of the request, the contents contain the user's username and password. A server can easily parse the data and do something with it. In this case, it can authenticate the user.
|
||||
|
||||
POST requests are used to send data to a server. A server will process the data and perform an action or store the data.
|
||||
|
||||
We have been talking a lot about how a server can process requests and send responses. How do programmers develop a server to handle HTTP requests? With PHP!
|
||||
|
||||
PHP was built with web server development in mind. Let us write our first PHP server script.
|
58
content/web/03-http-server.md
Normal file
58
content/web/03-http-server.md
Normal file
@@ -0,0 +1,58 @@
|
||||
In PHP, you usually use a separate web server program that accepts HTTP requests and passes them to PHP to create a response. Common examples of separate web server programs are Apache and Nginx. However, PHP has a built in web server we can use during development.
|
||||
|
||||
To use the development web server, open a terminal and a new folder for holding your code. Create a file called `index.php` and put this PHP code in it:
|
||||
```php
|
||||
<?php
|
||||
|
||||
echo 'Hello World!';
|
||||
```
|
||||
Go back to your terminal and start a PHP web server using this command:
|
||||
```bash
|
||||
php -S localhost:8080
|
||||
```
|
||||
Now, you can open `localhost:8080` in your web browser and you will see 'Hello World!' in the content of the page.
|
||||
|
||||
Next, we can use PHP to analyze all the information about the HTTP request sent from the browser to your PHP script. Change your `index.php` to have this code:
|
||||
```php
|
||||
<?php
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$uri = $_SERVER['REQUEST_URI'];
|
||||
$protocol = $_SERVER['SERVER_PROTOCOL'];
|
||||
$headers = getallheaders();
|
||||
|
||||
echo "$method $uri $protocol <br/>";
|
||||
foreach ($headers as $key => $header) {
|
||||
echo "$key: $header <br/>";
|
||||
}
|
||||
```
|
||||
Reload `localhost:8080` and you will see the main request line and all of the headers printed on the web page. The `<br/>` tag is HTML for a new line. Since we are outputting to a web browser, we can no longer use `"\n"` to create a new line.
|
||||
|
||||
By default, PHP will generate the necessary response line and headers. If you open your browser console and open the network tab, you can see the response code and headers.
|
||||
```http
|
||||
HTTP/1.1 200 OK
|
||||
Host: localhost:8080
|
||||
Date: Sun, 28 Apr 2019 10:19:25 -0500
|
||||
Connection: close
|
||||
X-Powered-By: PHP/7.2.17
|
||||
Content-type: text/html; charset=UTF-8
|
||||
```
|
||||
PHP set the response code to `200 OK` and the content type to `text/html`. Even though PHP will output good defaults, we can change them in our code if we want. Update your `index.php` file with this code:
|
||||
```php
|
||||
<?php
|
||||
|
||||
http_response_code(404);
|
||||
header('Content-Type: text/plain');
|
||||
|
||||
echo "Not Found!";
|
||||
```
|
||||
We are changing the status code to `404 Not Found` and the content type to plain text. If you open `localhost:8080` in your browser, you will now see this HTTP response in your console:
|
||||
```http
|
||||
HTTP/1.1 404 Not Found
|
||||
Host: localhost:8080
|
||||
Date: Sun, 28 Apr 2019 10:26:40 -0500
|
||||
Connection: close
|
||||
X-Powered-By: PHP/7.2.17
|
||||
Content-type: text/plain;charset=UTF-8
|
||||
```
|
||||
PHP added the other necessary headers for the response, but this time used `404` in the main response line and set the `Content-type` header to `text/plain`.
|
Reference in New Issue
Block a user