two file lessons

master
Matt Huntington 7 years ago
parent 3766332db7
commit 5d14cc808b

388
PHP.md

@ -5,33 +5,35 @@
1. Download [MAMP] (https://www.mamp.info/en/downloads/) 1. Download [MAMP] (https://www.mamp.info/en/downloads/)
1. Double click .pkg file and follow prompts 1. Double click .pkg file and follow prompts
1. Double click /Applications/MAMP/MAMP 1. Double click /Applications/MAMP/MAMP
1. Point MAMP to working directory 1. Tell MAMP to where your files are
- Click on Preferences - Click on Preferences
- Click on Web Server - Click on Web Server
- Click the folder icon next to "Document Root" and find a suitable directory to work out of - Click the folder icon next to "Document Root" and find a suitable directory to work out of
- Click OK - Click OK
1. In your Document Root, create `index.php`.
1. Go to <http://localhost:8888/> 1. Go to <http://localhost:8888/>
- If no file is specified in the URL after the port, MAMP will look for `index.php`
1. Error logs are in /Applications/MAMP/logs/ 1. Error logs are in /Applications/MAMP/logs/
- `tail -f php_error.log` - use `tail -f php_error.log` to watch the end of the log file in case something breaks
1. MAMP stands for Mac, Apache, MySQL, PHP 1. MAMP stands for Mac, Apache, MySQL, PHP
- this describes the tech stack - Mac
- Mac - Your OS
- Your OS - Apache
- Apache - A pre-build web server that serves static files
- A pre-build web server that serves static files - It is extendable with various modules that allows it to do many things easily
- Is extendable with various modules that allows it to do many things easily - MySQL
- MySQL - Your Database
- Your Database - PHP
- PHP - A module for Apache that allows it to serve dynamic data
- A module for Apache that allows it to server dynamic data
## Basics ## Basics
### Tags ### Tags
Because this is all run on top of Apache, the initial assumption is that we're serving static HTML files Because this is all run on top of Apache, the initial assumption is that we're serving static HTML files
- We need `<?php ?>` tags to show that we're writing PHP - We need `<?php ?>` tags to show that we're writing PHP
- Think of this as if Apache/PHP is server.js and we're just writing EJS - Think of this as if Apache/PHP is server.js and we're writing EJS
Instead of `<%= %>` you have `<?= ?>` or `<?php echo ?>` Instead of `<%= %>` you have `<?= ?>` or `<?php echo ?>`
@ -59,41 +61,62 @@ Use a $ before a variable name to tell php it is a variable. Assignment is stan
$my_first_var; //declare $my_first_var; //declare
$my_first_var = 2; //assignment $my_first_var = 2; //assignment
$my_second_var = 3; //declare and assign $my_second_var = 3; //declare and assign
echo $my_first_var; //print this variable to the page
echo $my_second_var; //print this variable to the page
?> ?>
``` ```
### Data Types ### Data Types
PHP has the following basic data types:
Strings:
```php ```php
<?php <?php
$x = "my string"; $x = "my string";
var_dump($x); var_dump($x);
?> ?>
``` ```
Integers:
```php ```php
<?php <?php
$x = 5985; $x = 5985;
var_dump($x); var_dump($x);
?> ?>
``` ```
Floats:
```php ```php
<?php <?php
$x = 10.365; $x = 10.365;
var_dump($x); var_dump($x);
?> ?>
``` ```
Booleans:
```php ```php
<?php <?php
$x = true; $x = true;
var_dump($x); var_dump($x);
?> ?>
``` ```
Arrays:
```php ```php
<?php <?php
$cars = array("Volvo","BMW","Toyota"); $cars = array("Volvo","BMW","Toyota");
var_dump($cars); var_dump($cars);
?> ?>
``` ```
NULL:
```php ```php
<?php <?php
$x = null; $x = null;
@ -103,7 +126,7 @@ var_dump($x);
### String Operators ### String Operators
Use a `.` or `.=` to combine strings. Use a `.` or `.=` to combine strings. Works just like `+` and `+=`
```php ```php
<?php <?php
@ -115,16 +138,25 @@ Use a `.` or `.=` to combine strings.
?> ?>
``` ```
Some kinds of string interpolation work:
```php
<?php
$x = 5;
echo "I have $x pizzas";
?>
```
### Arithmetic Operators ### Arithmetic Operators
```php ```php
<?php <?php
1 + 1; //2 echo 1 + 1; //2
2 - 1; //1 echo 2 - 1; //1
3 * 2; //6 echo 3 * 2; //6
12 / 3; //4 echo 12 / 3; //4
5 % 2; //1 modulus echo 5 % 2; //1 modulus
2 ** 3 //8 exponents echo 2 ** 3 //8 exponents
?> ?>
``` ```
@ -132,8 +164,11 @@ Use a `.` or `.=` to combine strings.
```php ```php
<?php <?php
$x = 2;
$x++; //increment by 1; $x++; //increment by 1;
echo $x;
$x--; //decrement by 1; $x--; //decrement by 1;
echo $x;
?> ?>
``` ```
@ -142,10 +177,15 @@ Use a `.` or `.=` to combine strings.
```php ```php
<?php <?php
$my_var = 1; $my_var = 1;
$my_var += 1; //$my_var = $my_var + 1; echo $my_var;
$my_var -= 1; //$my_var = $my_var - 1; $my_var += 3; //$my_var = $my_var + 1;
echo $my_var;
$my_var -= 2; //$my_var = $my_var - 1;
echo $my_var;
$my_var *= 2; //$my_var = $my_var * 2; $my_var *= 2; //$my_var = $my_var * 2;
echo $my_var;
$my_var /= 2; //$my_var = $my_var / 2; $my_var /= 2; //$my_var = $my_var / 2;
echo $my_var;
?> ?>
``` ```
@ -153,33 +193,40 @@ Use a `.` or `.=` to combine strings.
### Formats ### Formats
Format 1: The traditional format works great:
```php ```php
<?php <?php
if(condition){ $x = 1;
if($x > 2){
echo "x > 2";
} }
elseif(condition2){ elseif($x < 2){
echo "x > 2";
} }
else{ else{
echo "x == 2";
} }
?> ?>
``` ```
Format 2: If you have html and don't want to have lines that look like `<?php } ?>`, you can use the following style of if/else:
```php ```php
<?php if(condition): ?> <?php $x = 1; ?>
condition1 <?php if($x > 2): ?>
<?php elseif(condition2): ?> <code>x &gt; 2</code>
condition2 <?php elseif($ < 2): ?>
<code>x &lt; 2</code>
<?php else: ?> <?php else: ?>
else <code>x == 2</code>
<?php endif; ?> <?php endif; ?>
``` ```
### Comparison Operators ### Comparison Operators
Equality:
```php ```php
<?php <?php
$x == $y; //equal $x == $y; //equal
@ -220,7 +267,7 @@ Standard array functionality
$cars = array("Volvo", "BMW", "Toyota"); $cars = array("Volvo", "BMW", "Toyota");
$cars[4] = 'asdf'; //can be in indexes that don't yet exist $cars[4] = 'asdf'; //can be in indexes that don't yet exist
$cars[] = "added to end"; //pushes onto array $cars[] = "added to end"; //pushes onto array
echo "I like " . $cars[0] . ", " . $cars[4] . " and " . $cars[5] . "."; echo "I like " . $cars[0] . ", " . $cars[4] . " and " . $cars[5] . "."; //access arrays normally
echo count($cars); //prints length of array echo count($cars); //prints length of array
print_r($cars); //prints contents of array in nicer format than var_dump print_r($cars); //prints contents of array in nicer format than var_dump
?> ?>
@ -228,7 +275,7 @@ print_r($cars); //prints contents of array in nicer format than var_dump
### Associative Arrays (hashes) ### Associative Arrays (hashes)
These are very similar to Ruby hashes These are very similar to JavaScript objects, but are accessed like arrays:
```php ```php
<?php <?php
@ -247,17 +294,22 @@ These are very similar to Ruby hashes
$x = 1; $x = 1;
while($x <= 5) { while($x <= 5) {
echo "The number is: $x <br>"; echo "The number is: $x <br/>";
$x++; $x++;
} }
?> ?>
``` ```
Alternative syntax:
```php ```php
<?php $x = 1;?> <ul>
<?php while($x <= 5): ?> <?php $x = 1;?>
<li><?= $x ?></li> <?php while($x <= 5): ?>
<?php $x++ ?> <li><?= $x ?></li>
<?php endwhile; ?> <?php $x++ ?>
<?php endwhile; ?>
</ul>
``` ```
### For ### For
@ -265,31 +317,41 @@ while($x <= 5) {
```php ```php
<?php <?php
for ($x = 0; $x <= 10; $x++) { for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>"; echo "The number is: $x <br/>";
} }
?> ?>
``` ```
Alternative syntax:
```php ```php
<?php for ($x = 0; $x <= 10; $x++): ?> <ul>
<li>The number is: <?= $x ?></li> <?php for ($x = 0; $x <= 10; $x++): ?>
<?php endfor; ?> <li>The number is: <?= $x ?></li>
<?php endfor; ?>
</ul>
``` ```
### Foreach ### Foreach
This is like `for of` in JS:
```php ```php
<?php <?php
$colors = array("red", "green", "blue", "yellow"); $colors = array("red", "green", "blue", "yellow");
foreach ($colors as $key => $value) { foreach ($colors as $key => $value) {
echo $key . ": $value <br>"; echo $key . ": $value <br/>";
} }
?> ?>
``` ```
Alternative syntax:
```php ```php
<?php $colors = array("red", "green", "blue", "yellow"); ?> <?php $colors = array("red", "green", "blue", "yellow"); ?>
<?php foreach ($colors as $key => $value): ?> <?php foreach ($colors as $key => $value): ?>
<?= $key ?>: <?=$value?> <br> <?= $key ?>: <?=$value?><br/>
<?php endforeach ?> <?php endforeach ?>
``` ```
@ -300,242 +362,16 @@ This works for associative arrays:
$ages = array("Peter" => 35, "Ben" => 37, "Joe" => "43"); $ages = array("Peter" => 35, "Ben" => 37, "Joe" => "43");
foreach ($ages as $key => $value) { foreach ($ages as $key => $value) {
echo $key . ": $value <br>"; echo $key . ": $value <br/>";
} }
?> ?>
``` ```
Alternative syntax:
```php ```php
<?php $ages = array("Peter" => 35, "Ben" => 37, "Joe" => "43"); ?> <?php $ages = array("Peter" => 35, "Ben" => 37, "Joe" => "43"); ?>
<?php foreach ($ages as $key => $value): ?> <?php foreach ($ages as $key => $value): ?>
<?= $key ?>: <?=$value?> <br> <?= $key ?>: <?=$value?> <br/>
<?php endforeach ?> <?php endforeach ?>
``` ```
## Functions
```php
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
```
## Convenience Methods
### Strings
Count a string's length
```php
<?php
echo strlen("Hello world!"); // outputs 12
?>
```
Count number of words in a string
```php
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
```
Reverse a string
```php
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
```
Find a sub string in a string
```php
<?php
echo strpos("Hello world world!", "world"); // outputs 6
//search from the right
echo strrpos("Hello world world!", "world"); // outputs 12
?>
```
Replace text within a string
```php
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
```
Get a substring based on character index
```php
<?php
//second param is index (0 based, like an array)
echo substr("Hello world", 3); // outputs 'lo world'
//third param is length of string
echo substr("Hello world", 3, 4); // outputs 'lo w'
?>
```
Turn a string into an array based on some delimeter
```php
<?php
$the_string = "Some sentence goes here";
$string_array = explode(" ", $the_string);
var_dump($string_array);
?>
```
### Sorting Arrays
Various functions for sorting arrays. Can be done arithmetically or alphabetically, depending on content
- sort() - sort arrays in ascending order
- rsort() - sort arrays in descending order
- asort() - sort associative arrays in ascending order, according to the value
- ksort() - sort associative arrays in ascending order, according to the key
- arsort() - sort associative arrays in descending order, according to the value
- krsort() - sort associative arrays in descending order, according to the key
These functions affect the actual array they are called on.
```php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
print_r($cars); //BMW, Toyota, Volvo
```
## Classes and Objects
### Public Members
```php
<?php
class Car {
public $wheels = 4; // public var can be accessed outside class definition
}
$my_car = new Car();
print_r($my_car);
$my_car->wheels = 3;
print_r($my_car);
?>
```
### Constructors
```php
<?php
class Car {
public $wheels;
public function __construct($num_wheels){ // runs at beginning of object creation
$this->wheels = $num_wheels;
}
}
$my_car = new Car(4);
?>
```
### Protected Members
```php
<?php
class Car {
protected $wheels; // cannot be accessed outside class definition
//must define getters...
public function getWheels(){
return $this->wheels;
}
public function __construct($num_wheels){ // runs at beginning of object creation
$this->wheels = $num_wheels;
}
}
$my_car = new Car(4);
echo $my_car->getWheels();
echo $my_car->wheels; //error: cannot access protected property
?>
```
### Statics
```php
<?php
class Car {
protected $wheels; // cannot be accessed outside class definition
//must define getters...
public function getWheels(){
return $this->wheels;
}
public function __construct($num_wheels){ // runs at beginning of object creation
$this->wheels = $num_wheels;
}
}
class CarFactory{
static protected $cars = array();
static public function create($num_wheels){
$new_car = new Car($num_wheels);
self::$cars[] = $new_car;
return $new_car;
}
static public function find($index){
return self::$cars[$index];
}
}
$my_car = CarFactory::create(2);
$my_car2 = CarFactory::create(4);
print_r($my_car);
print_r(CarFactory::find(1));
print_r(CarFactory::$cars); //errors out: protected
?>
```
### Inheritance
```php
<?php
class Car {
protected $wheels; //accessible by child class, not outside class, though
private $engine_on = false; //unaccessible by child class
public function __construct($num_wheels){ // runs at beginning of object creation
$this->wheels = $num_wheels;
}
public function getWheels(){
return $this->wheels;
}
public function start(){
$this->engine_on = true;
}
}
class Humvee extends Car {
protected $armour = 10;
public function takeDamage($damage){
$this->armour -= $damage;
}
public function loseWheel(){
$this->wheels--; //can access parent $wheels member
}
//can extend parent's start function
public function start(){
parent::start(); //run parent's start function
//parent::$engine_on = false; //errors out: cannot access private member of parent
echo "WELCOME TO THE JUNGLE...";//then do something else
}
}
$my_humvee = new Humvee(6);
print_r($my_humvee);
$my_humvee->loseWheel();
print_r($my_humvee);
$my_humvee->takeDamage(6);
print_r($my_humvee);
$my_humvee->start();
print_r($my_humvee);
?>
```

@ -0,0 +1,261 @@
#Intermediate PHP
## Functions
```php
<?php
function greet($name) {
echo "Hello $name";
}
writeMsg("Matt"); // call the function
?>
```
## Convenience Methods
PHP has lots of global functions that will help you out:
### Strings
Count a string's length
```php
<?php
echo strlen("Hello world!"); // outputs 12
?>
```
Count number of words in a string
```php
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
```
Reverse a string
```php
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
```
Find a sub string in a string
```php
<?php
echo strpos("Hello world world!", "world"); // outputs 6
//search from the right
echo strrpos("Hello world world!", "world"); // outputs 12
?>
```
Replace text within a string
```php
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
```
Get a substring based on character index
```php
<?php
//This gets all remaining characters starting at the index specified in the string (0 based, like an array)
echo substr("Hello world", 3); // outputs 'lo world'
//third param is length of string to retrieve
echo substr("Hello world", 3, 4); // outputs 'lo w'
?>
```
Turn a string into an array based on some delimiter:
```php
<?php
$the_string = "Some sentence goes here";
$string_array = explode(" ", $the_string);
var_dump($string_array);
?>
```
### Sorting Arrays
Various functions for sorting arrays. Can be done arithmetically or alphabetically, depending on content
- sort() - sort arrays in ascending order
- rsort() - sort arrays in descending order
- asort() - sort associative arrays in ascending order, according to the value
- ksort() - sort associative arrays in ascending order, according to the key
- arsort() - sort associative arrays in descending order, according to the value
- krsort() - sort associative arrays in descending order, according to the key
These functions affect the actual array they are called on.
```php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
print_r($cars); //BMW, Toyota, Volvo
rsort($cars);
print_r($cars); //Volco, Toyota, BMW
```
Now with associative arrays:
```php
$ages = array("Peter" => 35, "Ben" => 37, "Joe" => "43");
asort($ages);
print_r($ages);
ksort($ages);
print_r($ages);
arsort($ages);
print_r($ages);
krsort($ages);
print_r($ages);
```
## Classes and Objects
### Public Members
```php
<?php
class Car {
public $wheels = 4; // public var can be accessed outside class definition
}
$my_car = new Car();
print_r($my_car);
$my_car->wheels = 3;
print_r($my_car);
?>
```
### Constructors
```php
<?php
class Car {
public $wheels;
public function __construct($num_wheels){ // runs at beginning of object creation
$this->wheels = $num_wheels;
}
}
$my_car = new Car(4);
print_r($my_car);
?>
```
### Protected Members
But what if you don't want someone to modify the number of wheels of a car after it is created?
You can set a method or member to `private` and any instance will not be able to read or write that value. It is only accessible from within the class itself
```php
<?php
class Car {
protected $wheels; // cannot be accessed outside class definition
//you must define public getters in order to see how many wheels a car has
public function getWheels(){
return $this->wheels;
}
public function __construct($num_wheels){
$this->wheels = $num_wheels;
}
}
$my_car = new Car(4);
echo $my_car->getWheels();
echo $my_car->wheels; //error: cannot access protected property
$my_car->wheels = 4; //error
?>
```
### Statics
You can have `static` members and methods that accessible only on the class itself, not on instances of the class.
```php
<?php
class Car {
protected $wheels;
public function getWheels(){
return $this->wheels;
}
public function __construct($num_wheels){
$this->wheels = $num_wheels;
}
}
class CarFactory{
static protected $cars = array(); // the array is protected
static public function create($num_wheels){
$new_car = new Car($num_wheels);
self::$cars[] = $new_car;
return $new_car;
}
static public function find($index){
return self::$cars[$index];
}
}
$my_car = CarFactory::create(2);
$my_car2 = CarFactory::create(4);
print_r($my_car);
print_r(CarFactory::find(1));
print_r(CarFactory::$cars); //errors out: protected
?>
```
### Inheritance
Protected members/methods can be used by inheriting classes, private members/methods cannot
```php
<?php
class Car {
protected $wheels; //accessible by child class, not outside class, though
private $engine_on = false; //unaccessible by child class
public function __construct($num_wheels){
$this->wheels = $num_wheels;
}
public function getWheels(){
return $this->wheels;
}
public function start(){
$this->engine_on = true;
}
}
class Humvee extends Car {
protected $armour = 10;
public function takeDamage($damage){
$this->armour -= $damage;
}
public function loseWheel(){
$this->wheels--; //can access parent class $wheels member because it is protected
}
//can extend parent's start function
public function start(){
parent::start(); //run parent's start function
//parent::$engine_on = false; //errors out: cannot access private member of parent
echo "WELCOME TO THE JUNGLE...";//then do something else
}
}
$my_humvee = new Humvee(6);
print_r($my_humvee);
$my_humvee->loseWheel();
print_r($my_humvee);
$my_humvee->takeDamage(6);
print_r($my_humvee);
$my_humvee->start();
print_r($my_humvee);
?>
```
Loading…
Cancel
Save