PHP

Basic Concepts

PHP Basic Concepts
PHP as a Social Activity

Presented by Sam Likins
PHP as a Social Activity

Topics

In this presentation we'll cover the following:

  • Parsing – Reading & Interpreting of a program
  • Basic Syntax – The necessary framework of the language
  • Types – Scalar & Compound value distinction
  • Variables – A place to store a (read & write) value
  • Constants – A place to store a (read-only) value
  • Operators – Deriving a value from one or more other values
  • Expressions – Creating the instructions
  • Control Structures – From calculating to computing
  • Functions – The macros of high level languages

Parsing

Reading & Interpreting of a program

In this section we'll cover:

  • Compiled vs. Interpreted Languages – Programming work-flow
  • PHP Input & Output – Processing the stream of data
  • Preprocessing – Human-readable code to executing program
  • Zend Engine (v2.0) – The Virtual Machine
  • Execution of a PHP Script – Peeking behind the virtual curtain

Compiled vs. Interpreted Languages

Programming work-flow

Compiled
  • Write human-readable source code
  • Use a compiler to translate source code into machine code
  • Correct compile-time errors
  • Execute machine code with a debugger
  • Correct run-time errors
  • Repeat until successful…
Interpreted
  • Write human-readable source code
  • Execute source code for debugging with an interpreter
  • Correct syntax & run-time errors
  • Repeat until successful…

PHP Input & Output

Processing the stream of data

PHP is an interpreted language, not a compiled one:

  • Takes input (file or stream) containing text and/or PHP instructions
  • Creates output (stream), most commonly HTML

Since PHP 4: The PHP parser preprocesses the input to produce opcodes for processing by the Zend Engine.

Preprocessing

Human-readable code to executing program

  1. Preprocessor
    1. Lexical Analyzer (lexer)
      1. Reads in the human-readable source code
      2. Interprets the source code into machine-digestible tokens
      3. Passes the tokens to the Parser
    2. Parser
      1. Creates an operation code array (opcode / op array) from the tokens
        – The op array is also known as an abstract syntax tree (AST)
      2. Passes the op array to the Executor
  2. Executor
    1. Steps through the op array
    2. Executing each opcode in the op array with the Zend Engine

Zend Engine (v2.0)

The Zend Engine simulates an ideal computer. The VM architecture provides hardware independent flexibility & portability. While a standard (x86) computer processor has 75 base operations, the Zend Engine has approximately 150 instruction (opcodes).

The Virtual Machine

  • Keeps track of requests
  • Processes scripting files
  • Handles variables & resources

The VM opcode set includes simple logic & math operations, as well as complex operations such as include(). A VM is always slower than the host machine; some speed penalty is regained by performing complex instructions as a single VM operation.

Execution of a PHP Script

Peeking behind the virtual curtain

This diagram indicates why PHP is an interpreter (run-time compiler). A true compiler can't compile during execution. PHP loads & compiles each file as it's required.

Basic Syntax

The necessary framework of the language

In this section we'll cover:

  • PHP Tags – Opening & closing tags
  • Escaping – Switching the interpreter on & off
  • Instruction Separation – Individual statements made clear
  • Comments – Human readable annotations

PHP Tags

Opening & Closing tags

  1. <?php?> Always Available
  2. <script language="php"></script> Always Available
  3. <??> Short Style
  4. <?=?> Echo - Short Style
  5. <%%> ASP Style
  6. <%=%> Echo - ASP Style

The Opening tag tells the interpreter to turn on

The Closing tag tells the interpreter to turn off

The Echo tags are short for <?php echo; ?>

Escaping

Switching the interpreter on & off

Everything outside of the PHP tags is escaped.


 <html>
     <body>
         <h1><?php echo $title; ?></h1>
     </body>
 </html>
						

Escaped content is passed threw as output.


 <html>
     <body>
         <h1>Escaping PHP</h1>
     </body>
 </html>
						

Escaping


 <html>
     <body>
         <h1><?php echo $title; ?>
         </h1>
     </body>
 </html>
						

A new-line character directly after a closing tag is ignored.


 <html>
     <body>
         <h1>Escaping PHP</h1>
     </body>
 </html>
						

Escaping

Escaping large blocks of output is more efficient than using an output function or command, such as echo or print.

Parsing in this manner allows PHP to be embedded in all sorts of different documents.

  • HTML
  • CSS
  • SVG
  • CSV
  • XML
  • JS

Instruction Separation

Individual statements made clear

Statements are separated with a single semicolon.


 <?php

 $name = "PHPaaSA";
 echo $name

 ?>
						

A semicolon is not necessary for the last statement of a PHP block.

Comments

Human readable annotations

  • Single-line – Comment to the end of the line or PHP block
    • XML style PHP tags (</script>) don't break out of comments
    • // – C++ style comments
    • # – Perl style comments
  • Multi line – Comment out large blocks of content
    • /* & */ – C style comments
    • First close comment tag ends the comment, don't nest Multi line comments.

Types

Scalar & Compound value distinction

In this section we'll cover:

  • Scalar Types – Single unit of data
  • Compound Types – Types that store other types
  • Special Types– Non standard types
  • Documentation Types– Notational types

Scalar Types

  • Boolean – Two possible values
  • Integer Whole Numbers, fractions need not apply
  • Float Real Numbers, decimals included
  • String Characters, strung together

Boolean

Two possible values

User the keywords TRUE or FALSE

Keywords are case-insensitive

Integer

Whole Numbers, fractions need not apply

Optionally preceded with a sign (-, +)

Specified in several bases

Binary - Base 2

Specified by preceding with 0b

Available since ver 5.4

Octal - Base 8

Specified by preceding with 0

Decimal - Base 10

Default Base

Hexadecimal - Base 16

Specified by preceding with 0x

Float

Real Numbers, decimals included

Specified in three ways

1.234

1.2e3

7E-10

String

Characters, strung together

1 Character is 1 bite

Specified four different ways

Single-quote

Simplest way to specify a string

To specify a single-quote in the string precede (escape) it with a backslash \

To specify a backslash precede (escape) it with a backslash \String

Double-quote

Interpret more escape sequences than single-quote

\n - Linefeed

\r - Carriage return

\t - Horizontal tab

\v - Vertical tab

\e - Escape

\f - Form feed

\\ - Backslash

\$ - Dollar sign

\" - Double-quote

Variables will be evaluated and inserted in the string

Heredoc syntax

Opened with <<<

Followed by a name (optional enclosed in double-quotes)

With a newline directly after

Closed with the same identifier as it's opened with

Must start on the first character of the line

Must be the only thing on the line, with exception to a semicolon

Interprets the same set as double-quote, minus the double quote escape

Nowdoc syntax

Available since ver 5.3

Opened with the same identifier as Heredoc

However the following name is enclosed in single-quotes

Closed using the same rules as Heredoc

Compound Types

  • Array – Sets of paired values
  • Object – Bringing class into the work

Array

Sets of paired values

An Ordered Map containing Key-Value pairs

A Key can be ether an Integer or a String

The Value can be any Type

Object

Bringing class into the work

An Instantiated Class

Class - A definition of a collection of variables and functions

stdClass

Predefined Interfaces

Traversable

Iterator

IteratorAggregate

ArrayAccess

Serializable

Closure

Standard PHP Library - SPL - Basic Extension

User Defined - An Instantiated User Defined Class

Special Types

  • NULL – No value is still a value
  • Resource – Reaching the external

NULL

No value is still a value

Resource

Reaching the external

Documentation Types

  • mixed –
  • number
  • callback & callable
  • void
  • $…

Variables

A place to store a (read & write) value.

In this section we'll cover:

  • Declaration – Defining the variable prior to first use (not required in PHP)
  • Typing – Specifying a type for the variable (not done in PHP)
  • Scope – The context which the variable can be accessed
  • Signifier – Variables are preceded with a '$'
  • Name – The name of the variable can contain underscore, letters, and numbers
  • Predefined Variables – Populated by the system environment and active code
  • Variable variables – Calling for the contents a variable with the variables name

Declaration

Defining the variable prior to first use (not required in PHP)

Typing

Specifying a type for the variable (not done in PHP)

Scope

The context which the variable can be accessed

Global - Within a code block the global keyword will allow access to global variables

Static - Only visible within its own code block

Signifier

Variables are preceded with a '$'

Name

The name of the variable can contain underscore, letters, and numbers

The first character can be an underscore or a letter

Variable names are case-sensitive

Predefined Variables

Populated by the system environment and active code

Superglobals - Arrays containing environmental values available in all scopes

$GLOBALS - All variables within the global scope

$_SERVER - Execution environment values

$_GET - HTTP GET variables

$_POST - HTTP POST variables

$_COOKIE - HTTP Cookie variables

$_REQUEST - HTTP GET, POST, and COOKIE variables

$_FILES - HTTP File Upload variables

$_SESSION - Session variables

$_ENV - Environment variables

$php_errormsg - Last error message

$argc - Number of arguments passed to the script

$argv - Array of arguments passed to the script

Variable variables

Calling for the contents a variable with the variables name

Constants

A place to store a (read-only) value

In this section we'll cover:

  • Declaration – Defining the constant prior to first use
  • Values – Types of data to store
  • Magic Constants – Do noting, there here

Declaration

Defining the constant prior to first use

Values

Types of data to store

Scalar data is allowed

Magic Constants

Do noting, there here

  • __LINE__ – Current line number in the file
  • __FILE__ – Full path and filename of the file
  • __DIR__ – Path of the file
  • __FUNCTION__ – Name of current function
  • __CLASS__ – Name of current class
  • __TRAIT__ – Name of current trait
  • __METHOD__ – Name of current method
  • __NAMESPACE__ – Name of current namespace

Expressions

Creating the instructions

In this section we'll cover:

Operators

Deriving a value from one or more other values

In this section we'll cover:

Control Structures

From calculating to computing

In this section we'll cover:

The difference between a calculator & a computer is the ability to have conditional branching.

Functions

The macros of high level languages

In this section we'll cover: