Learning PHP

  • Semicolons are mandatory in PHP

  • PHP code can be embedded in HTML pages

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    <html>
    <head>
      <title>Learning PHP</title>
    </head>
    <body>
    
    <?php
        echo "Hello World !";
    ?>
    
    </body>
    </html>
    
  • Variables are declared with $. For example: $myvar = "This is my variable". PHP is not strict with the data types of the variables.

  • To concatenate strings use .. For example: echo "Hello, " . $name.

  • Creating array : $people = array("Alice", "Bob", "Cathy")

  • Looping through array

    1
    2
    3
    4
    5
    6
    
    <?php
    $people = array("Alice", "Bob", "Cathy")
    foreach ($people as $person) {
      echo $person . ' ';
    }
    ?>
    

Hello World

  • PHP start development webserver : php -S localhost:4000
  • PHP is tightly coupled with HTML. You can write html code in .php file and the file renders like a html file when opened in a browser.
  • Semicolons are mandatory in PHP

Variables

  • To include a variable in echo statement:
    1
    2
    3
    4
    
    <?php
      $characterName = "John";
      echo "There once lived a man named $characterName";
    ?>
    

Data Types

  • String : $phrase = "Hello, "
  • Integer : $number = 30 (can be positive or negative)
  • Decimal (floating numbers) : $gpa = 3.33
  • Boolean : $loggedIn = true
  • Null value : null

Working with Strings

  • Convert string to lowercase : strtolower()
  • Convert string to uppercase : strtoupper()
  • Get string length : strlen()
  • String is an array of characters. The characters can be accessed by the index of a string. Ex: "Mike"[0] give M
  • Replacing sub strings : str_replace("Google", "Alphabet", $companyName);
  • Get sub string : substr($phrase, 8, 3) where 8 is the index of the starting character and 3 is the length of substring. If the length is not provided, then PHP gives the substring till the end of the phrase.

Working with Numbers

  • Basic math operations : +, -, *, /, %
  • Incrementing : $num++
  • Decrementing : $num--
  • Max of numbers : max(2, 10)
  • Min of numbers : min(2, 10)

Getting user input

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<html>
<head>
  <title>User Input</title>
</head>
<body>
  <form action="site.php" method="get">
    Name: <input type="text" name="name">
    <input type="submit">
  </form>
  <br>
  <?php echo $_GET["name"] ?>
</body>
</html>

Use $_POST["name"] for data sent through POST message

Arrays

  • Create array: $friends = array("asfds", "ddfvs", "rfdfs");
  • Array can store any data type
  • A new element can be added at any index position of the array. For example, in the above $friends array, I can add new friend at index 10 : $friends[10] = "Pot"
  • To get the total number of elements in array : count($friends)

Associative array

  • This is like dictionary in Python
  • Example: $grades = array("Jim"=>"A+", "Pam"=>"B-")
  • The keys must be unique
  • Get the number of elements : count($grades)

Functions

Function taking arguments

1
2
3
4
5
6
<?php
  function sayHi($name) {
    echo "Hello, $name";
  }
  sayHi("Badshah");
?>

Function with returns

1
2
3
4
5
6
7
8
<?php
  function cube($num) {
    return $num * $num * $num;
  }

  $cubeResult = cube(4);
  echo $cubeResult;
?>

If statements

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
  $isMale = false;
  $isTall = false;
  if ($isMale && $isTall) {
    echo "You are a tall male";
  } elseif ($isMale && !$isTall) {
    echo "You are a short male";
  } else {
    echo "You are not a male";
  }
?>

Switch statements

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php
  $grade = $_POST["grade"];
  switch($grade) {
    case "A": 
        echo "You did amazing";
        break;
    case "B":
        echo "You did pretty good";
        break;
    default:
        echo "Invalid grade";
  }
?>

While loops

1
2
3
4
5
6
7
<?php
  $index = 1;
  while($index <= 10) {
    echo "$index <br>";
    $index++;
  }
?>

Do-While loops

1
2
3
4
5
6
7
<?php
  $index = 6;
  do{
    echo "$index <br>";
    $index++;
  }while($index <= 5)
?>

For loops

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
  for($i = 1; $i <= 5; i++) {
    echo "$i <br>";
  }

  $luckyNumbers = array(4,6,24,346,231,357);
  for($i = 0; i < count($luckyNumbers); i++) {
    echo "$luckyNumbers[$i] <br>";
  }
?>

Comments

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
  // Single line comment
  echo "Comment";

  /*
  Multi
  line
  comment
  */
?>

Including HTML

1
2
<?php include "header.html" ?>
<?php include "footer.html" ?>

In the above example, header.html and footer.html are HTML files on the same directory as the php file.

Include PHP

article-header.php

1
2
3
<h2> <?php echo $title; ?> </h2>
<h4> <?php echo $author; ?> </h4>
Word count: <?php echo $wordCount; ?>

site.php

1
2
3
4
5
6
<?php
  $title = "My first post";
  $author = "Tester";
  $wordCount = 400;
  include "article-header.php";
?>

In a similar way, including a php file allows you to use the functions & variables defined in the included file.

Classes & Objects

  • Class is a specification of a custom data type
  • Object is an instance of a class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php
  class Book {
    var $title;
    var $author;
    var $pages;
  }

  $book1 = new Book;
  $book1->title = "Harry Potter";
  $book1->author = "JK Rowling";
  $book1->pages = 400;

  echo $book1->title;
?>

Constructors

  • Constructor is the function that gets called whenever we create an object of a class
  • Always named __construct()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php
  class Book {
    var $title;
    var $author;
    var $pages;

    function __construct($aTitle, $aAuthor, $aPages) {
      echo "New book created: $aTitle <br>";
      $this->title = $aTitle;
      $this->author = $aAuthor;
      $this->pages = $aPages;
    }
  }

  $book1 = new Book("Harry Potter", "JK Rowling", 400);
?>

Object functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
  class Book {
    var $title;
    var $author;
    var $pages;

    function __construct($title, $author, $pages) {
      echo "New book created: $aTitle <br>";
      $this->title = $title;
      $this->author = $author;
      $this->pages = $pages;
    }

    function toString() {
      echo "$this->title is written by $this->author and has $this->pages pages.";
    }
  }

  $book1 = new Book("Harry Potter", "JK Rowling", 400);
  $book1->toString();

?>

Getters and Setters

  • Visibility modifier : defines what different attributes of an object can code access
  • When a variable is declared using var, its public by default
  • Getters and setters are special functions written inside a class to get & set the (mostly private) attributes
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
  class Movie {
    public $title;
    private $rating;

    function __construct($title, $rating) {
      $this->title = $title;
      $this->setRating($rating);
    }

    function getRating() {
      return $this->rating;
    }

    function setRating($rating) {
      if ($rating == "G" || $rating == "PG" || $rating == "PG-13") {
        $this->rating = $rating;
      } else {
        $this->rating = "NR";
      }
    }
  }

  $avengers = new Movie("Avengers", "PG-13");
  echo $avengers->getRating();
?>

Inheritance

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php

  class Chef {
    function makeChicken() {
      echo "The chef makes chicken <br>";
    }
    function makeSalad() {
      echo "The chef makes salad <br>";
    }
    function makeSpecialDish() {
      echo "The chef makes bbq ribs <br>";
    }
  }

  $chef = new Chef();
  $chef->makeChicken();

  class ItalianChef extends Chef {
    function makePasta() {
      echo "The chef makes pasta";
    }
    function makeSpecialDish() {
      echo "The chef makes chicken parm <br>";
    }
  }

  $italianChef = new ItalianChef();
  $italianChef->makeChicken();
?>