php chapter 1 training

Post on 15-Jan-2015

3.341 Views

Category:

Technology

3 Downloads

Preview:

Click to see full reader

DESCRIPTION

PHP ZEND Certification TrainingChapter 1 Fundamentals

TRANSCRIPT

PHP Basics

Orlando PHP Meetup

Zend Certification Training

January 2008

Anatomy of a Web Request

What happens when you request index.php?Web server (Apache) loads handler, php

application and provides URL and POST data, if any.

PHP: Parse page to split code from htmlCompile codeExecute codeMerges code output with htmlStream back to Apache, which forwards to the users

browser.

PHP Syntax

Tags (Must be matched pairs)<?php code ?> - Recommended<? ?> - Frequently used, <?= ?> (auto echo)<% %>, <script language=“php”> </script>

WhitespaceInside script tags: Ignored

Just don’t break any <?php tags or function names.Outside script tags: Sent to output stream exactly

Case Sensitive$This != $this != $THIS

Comments

// Single line comment - Preferred# Single line comment – Valid but deprecated/* Multi-line

comment*/

/*** API Documentation Example** @param string $bar*/function foo($bar) { }

VariablesAll variables start with dollar sign: $

$scalar – Holds a single value$array[$index] – Single element of an array$object->method() – Object and method$object->property – Object and property

Variable variables: $$variablename$variablename = ‘size’;$$variablename == $size(Use sparingly, can drive mortal programmers

insane)

Language ConstructsCode Blocks – Wrapped in {}

{// Some commentsf(); // a function call}

Statements terminated with semicolon.Single or multiline:

echo(‘this is printed’ . ‘on a single ‘ . ‘line.’);

Data TypesScalar Types

boolean - A value that can only either be false (value == 0 or value = ‘’ or value ==‘0’) or true (any other value)

int - A signed numeric integer valueDecimal: 1234567890Octal: 01234567 (Leading zero)Hex: 0x1234567890ABCDEF

float - A signed floating-point valueDecimal: 12345.6789Exponential: 123.45e67 or 123.45E67

string - A collection of character or binary data

Data Types (2)Compound Types

Array – An ordered hash of key => value pairsKey evaluates to integer or stringValue may be any data type.

Object – Containers of data and code.

Special TypesResource – Handle to a file, database or

connectionNULL – A special value for an uninitialized

variable

Data Type ConversionLoosely typed

A single variable can contain different types over it’s lifespan

Mostly transparent, but can be forced$var = (int) (‘123’ + ‘456’) == 123456$var = (int) ‘123’ + ‘456’ == 579 (Early bind)Cannot convert TO a resource or class.

When converting to a boolean:false == 0, ‘0’, ‘’, null, unset()true == (! false) (Caution: ’00’ or ‘ ‘ == true)

Variable NamingMust start with a dollar sign: $Then a character (a-zA-z) or underscoreMay contain numbers (not first character)

Except variable variables$var = ‘123’$$var = ‘value’echo ${‘123’}; //outputs ‘value’

No punctuation or special charactersValid: $value, $value123, $_valNot Valid: $1value, $value.two, $value@home

Variable ScopeFunction

Defined when first referenced (var) or assigned to.Not inherited from the call stack.Disposed when function exits

GlobalDefined outside a functionInherit into a function with global() or

$GLOBALS[‘varname’]Limit use to improve maintainability

ClassClass properties are visible within the class via

$this->varname

Constantsdefine(‘CONSTANT’, ‘scalarvalue’);echo CONSTANT; //No $ or single quoteImmutable, scopeless, ONLY scalar values

(int, float, boolean, string)

Operators 1Assignment Operators

assigning data to variables ($a = 1; $b = $c = 2;)Value: $b = $a Reference: $b = &$a; (makes copy)

Arithmetic Operators performing basic math functions ($a = $b + $c;)

String Operators joining two or more strings ($a = ‘abc’ . ‘def’;)

Comparison Operators comparing two pieces of data ($boolean = $a or $b;)

Logical Operators performing logical operations on Boolean values

Operators 2Bitwise Operators

Manipulating bits using boolean math ($a = 2 & 4;)Error Control Operators

Suppressing errors ($handle = @fopen();)Execution Operators

Executing system commands ($a = `ls –la`;)Incrementing/Decrementing Operators

Inc. and dec. numerical values ($a += 1; $a++; ++$a;)

Type Operators Identifying Objects

Operator Precedence & AssociativityAssociativity Operator

left [

non-associative ++ -

non-associative ˜ - (int) (float) (string) (array) (object) @

non-associative instanceof

Right !

left * / %

left + - .

left << >>

non-associative < <= > >=

non-associative == != === !==

left &

left *

left |

left &&

left ||

left ? :

right = += -= *= /= .= %= &= |= ˆ= <<= >>=

left and

left xor

left or

left ,

Control StructuresIf – Then – Else

if (expression1) { // True expressions} elseif (expression2) { // Optional space between else and if} else { // Nothing else matches}

($a == $b) ? $truevalue : $falsevalue;

Switch statementDoes not need to evaluate on each

comparison $a = 0;

switch ($a) { // In this case, $a is the expression case true: // Compare to true // Evaluates to false break;case 0: // Compare to 0 // Evaluates to true break;default: // Will only be executed if no other conditions are met break;}

Iteration ConstructsWhile (pre-comparison)

$i = 0;while ($i < 10) { echo $i . PHP_EOL; $i++;}

Do (post comparison)$i = 0;

do { echo $i . PHP_EOL; $i++;} while ($i < 10);

for() and foreach()for(init ; compare ; increment) {}

for ($i = 0; $i < 10;$i++) { echo $i . PHP_EOL;}

foreach ($array as $element)$arr = array (‘one’, ‘two’, ‘three’);

foreach ($arr as $item){ echo $item . PHP_EOL;}

foreach ($assoc_array as $key => $item)$arr = array (‘one’ => ‘uno’, ‘two’ => ‘dos’);

foreach ($arr as $english => $spanish) { echo “$english means $spanish \n”;}

Breaking Out: break [n] Exits the current loop (for, foreach, while, do-while or switch but

NOT if) and optionally parents $i = 0;

while (true) { if ($i == 10) { break; } echo $i . PHP_EOL; $i++;}

for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 3; $j++) { if (($j + $i) % 5 == 0) { break 2; // Exit from this loop and the next one. } }} //break continues here

ContinueSkips rest of loop and restarts

for ($i = 0; $i < 10; $i++) { if ($i > 3 && $i < 6) { continue; } echo $i . PHP_EOL;}

Can also take an optional parameter to restart optional parents.

Errors and Error ManagementTypes of errors:

Compile-time errorsErrors detected by the parser while it is compiling a script.

Cannot be trapped from within the script itself.Fatal errors

Errors that halt the execution of a script. Cannot be trapped.Recoverable errors

Errors that represent significant failures, but can still be handled in a safe way.

WarningsRecoverable errors that indicate a run-time fault. Do not halt

the execution of the script.Notices

Indicate that an error condition occurred, but is not necessarily significant. Do not halt the execution of the script.

Error ReportingSet via INI configurations

error_reporting=E_ALL & ~E_NOTICEFrom code:

error_reporting(E_ALL & ~E_NOTICE)display_errors = on #Show in browserlog_errors = on # Write to log file or web

server log

Handling ErrorsGlobal error handling function

$oldErrorHandler = ’’; //Stores name of old functionfunction myErrorHandler($errNo, $errStr, $errFile, $errLine, $errContext) { global $oldErrorHandler; logToFile("Error $errStr in $errFile at line $errLine"); // Call the old error handler if ($oldErrorHandler) { $oldErrorHandler ($errNo, $errStr, $errFile, $errLine, $errContext); }}//Set up a new error handler function, returns the old handler function name$oldErrorHandler = set_error_handler(’myErrorHandler’);

Ignore & Check $return = @function_call($params); //Internal only

if ($return === FALSE) { //Handle Error}

SummaryLanguage fundamentals are building

blocks of programming.Build a strong foundation and your

architecture will follow.Be clear, concise and always explain why

when writing code. Pick a standard and stick with it.Don’t be afraid to read and reread the

documentationhttp://www.php.net/manual/

HomeworkWrite the classic “Hello World”

application. Build an index.php that prints out “Hello

[[name]]” 5 times in the middle of a page. Page needs to be fully formed html, <html>

through </html>.[[Name]] should be collected from the

$_REQUEST[‘name’] variable. If the [[name]] is less than 5 characters, it

should be in all capitals. Otherwise, print it out as received.

top related