php crash course - macq electronique 2010

50
PHP Crash Course Macq Electronique, Brussels 2010 Michelangelo van Dam

Upload: michelangelo-van-dam

Post on 01-Dec-2014

11.076 views

Category:

Technology


0 download

DESCRIPTION

Introduction to PHP and it's basic concepts

TRANSCRIPT

Page 1: Php Crash Course - Macq Electronique 2010

PHP Crash CourseMacq Electronique, Brussels 2010

Michelangelo van Dam

Page 2: Php Crash Course - Macq Electronique 2010

Targeted audience

experience with development languagesknowledge about programming routines

types and functions

this is not “development for newbies” !

Page 3: Php Crash Course - Macq Electronique 2010

Michelangelo van Dam

• Independent Consultant

• Zend Certified Engineer (ZCE)

- PHP 4 & PHP 5

- Zend Framework• Co-Founder of PHPBenelux• Shepherd of “elephpant” herdes

Page 4: Php Crash Course - Macq Electronique 2010

For more information, please check out our website http://www.macqel.eu

TAIL ORMAD E SO LU T IO NS

Macq électronique, manufacturer and developer, proposes you a whole series of electronic and computing-processing solutions for industry, building and road traffic.

Macq électronique has set itself two objectives which are essential for our company :

developing with competence and innovation earning the confidence of our customers

Macq électronique presents many references carried out the last few years which attest to its human and technical abilities to meet with the greatest efficiency the needs of its customers.

Page 5: Php Crash Course - Macq Electronique 2010

What is PHP ?

• most popular language for dynamic web sites• open-source (part of popularity)• pre-processed programming language- no need to compile• simple to learn (low entry level)• easy to shoot yourself in your foot ! (no kidding)

Page 6: Php Crash Course - Macq Electronique 2010

PHP is a “Ball of nails”

“When I say that PHP is a ball of nails, basically, PHP is just this piece of shit that you just put together—put all the parts together—and you throw it against the wall and it fucking sticks.”Terry Chay

Page 7: Php Crash Course - Macq Electronique 2010

History of PHP

• 1995: Rasmus Lerdorf created PHP- for maintaining his own resume on the web- called it “Personal Home Page”- improved it with a Form interpreter (PHP-FI)• 1997: Zeev Zuraski and Andi Gutmans- rewrote first parser for PHP v3- renamed it “PHP: Hypertext Preprocessor”• 1998: Zeev Zuraski and Andi Gutmans- redesigned the parser for PHP 4 (Zend Engine)- founded Zend Technologies, Inc.

Page 8: Php Crash Course - Macq Electronique 2010

Why PHP ?

Page 9: Php Crash Course - Macq Electronique 2010

Seriously, who uses PHP ?

“PHP is currently the most popular server-side web programming language. It runs 33,53%˙ of the websites on the Internet.”Source: wheel.troxo.com

˙ data from 2007 !!!

PHP powers adult websites !!!

Page 10: Php Crash Course - Macq Electronique 2010

Starting with PHP

• Minimum Requirements:- php hypertext preprocessor (www.php.net)- a text editor (notepad, textpad, vi, pico, emacs, …)• Preferred requirements:- LAMP: Linux, Apache, MySQL, PHP- WAMP: Windows, Apache, MySQL, PHP- WIMP: Windows, IIS, MS SQL, PHP- SPAM: Solaris, PHP, Apache, MySQL- Mac OS X

Page 11: Php Crash Course - Macq Electronique 2010

Where to start ?

http://php.net

Page 12: Php Crash Course - Macq Electronique 2010

Easy installation

http://www.zend.com/community/zend-server-ce

Page 13: Php Crash Course - Macq Electronique 2010

My first PHP codePut the following code in file “helloWorld.php”:<?php

echo 'Hello World';

?>

To execute this code you can just useuser@server: $ /usr/local/zend/bin/php ./helloWorld.php

And it will outputHello Worlduser@server: $

Page 14: Php Crash Course - Macq Electronique 2010

What about websites ?

Page 15: Php Crash Course - Macq Electronique 2010

Some dry theory first

• Basic syntax• Types• Variables• Constants• Expressions• Operators• Control Structures• Functions• Classes and Objects• Namespaces

• Exceptions• References Explained• Predefined Variables• Predefined Exceptions• Predefined Interfaces• Context options and

parameters

Same as on http://php.net/manual/en/langref.php

Page 16: Php Crash Course - Macq Electronique 2010

Basic syntax

• Escaping from HTML• Instruction separation• Comments

Page 17: Php Crash Course - Macq Electronique 2010

Escape from HTMLSimple escaping:<p>This is going to be ignored.</p><?php echo 'While this is going to be parsed.'; ?><p>This will also be ignored.</p>

Advanced escaping:<?php if ($expression) { ?> <strong>This is true.</strong> <?php} else { ?> <strong>This is false.</strong> <?php}?>

Page 18: Php Crash Course - Macq Electronique 2010

Instruction separation<?php echo 'This is a test';?>

<?php echo 'This is a test' ?>

<?php echo 'We omitted the last closing tag';

Page 19: Php Crash Course - Macq Electronique 2010

Comments<?php

// single line comment

if ($condition) { // another single line c++ style comment /* This is a multi-line comment that spans over multiple lines */ echo 'This is a test'; echo 'This is another test'; # with a single line shell style comment}

A common mistake is to nest multi-line comments !/* This multi-line comment /* has a nested multi-line comment spanning two lines */*/

The last */ will never be reached !!!

Page 21: Php Crash Course - Macq Electronique 2010

Scalar types

• boolean (have a TRUE or FALSE state)• integer (decimal, octal or hexadecimal)- positive numbers (1,204, …)- negative numbers (-9, -128, …)- hexadecimal numbers (0x1A, 0xFF, …)- octal numbers (0123, 0777, …)• float (a.k.a. floats, doubles, real numbers)- 1.234, 1.2e3, 7E-10, …• string

Page 22: Php Crash Course - Macq Electronique 2010

Single quoted strings<?phpecho 'this is a simple string'; // this is a simple string

echo 'this is a ' . 'combined string'; // this is a combined string

echo 'this is a multi- // this is a multi-line stringline string';

echo 'I\'m an escaped character string'; // I'm an escaped character string

$var = '[var]';echo 'this $var is not processed'; // this $var is not processed

Page 23: Php Crash Course - Macq Electronique 2010

Double quoted strings<?phpecho "this is a simple string"; // this is a simple string

echo "this is a " . "combined string"; // this is a combined string

echo "this is a multi- // this is a multi-line stringline string";

echo "I'm an escaped character string"; // I'm an escaped character string

$var = '[var]';echo "this $var is processed"; // this [var] is processed

Page 24: Php Crash Course - Macq Electronique 2010

Compound Types

• array• object

Page 25: Php Crash Course - Macq Electronique 2010

Arrays

• ordered map- collection of keys and values❖ keys: can only be an integer or a string❖ values: can be of any type

Page 26: Php Crash Course - Macq Electronique 2010

Example arrays$myArray = array (1, 2, 3, 4); // array[0] = 1; array[1] = 2; // array[2] = 3;

$myArray = array (1, 'Hello World'); // array[0] = 1; // array[1] = 'Hello World';

$myArray = array (1 => 'a', 2 => 'b'); // array[1] = 'a'; array[2] = 'b';

$myArray = array ('a' => 1, 'b' => 2); // array['a'] = 1; array['b'] = 2;

$myArray = array ( 'a' => array (1, 2, true), // array['a'] = array[0] = 1; // array[1] = 2; // array[2] = true; 'b' => array ( // array['b'] = 'a' = 1, // array['a'] = 1; 'b' = false, // array['b'] = false; 'c', // array[0] = 'c'; ),);

Page 27: Php Crash Course - Macq Electronique 2010

Objects<?phpclass foo{ function do_foo() { echo "Doing foo."; }}

$bar = new foo;$bar->do_foo();?>

OutputsDoing foo

More about objects in the advanced PHP session…

Page 28: Php Crash Course - Macq Electronique 2010

Special Types

• resource• NULL

Page 29: Php Crash Course - Macq Electronique 2010

Resource

• Special type- holds a reference to an external source❖ a database, a file, a stream, …- can be used to verify a resource type

Page 30: Php Crash Course - Macq Electronique 2010

NULL

• represents a variable with no value• a variable is considered null- when assigned the NULL constant- it has no value assigned yet- has been emptied by unset()

Page 31: Php Crash Course - Macq Electronique 2010

Pseudo Types

• mixed: used for any type• number: used for integers and floats• callback:- a function (name) is used as parameter- a closure or anonymous function (as of PHP 5.3)- cannot be a language construct

Page 32: Php Crash Course - Macq Electronique 2010

Type Juggling

• no explicit type definitions of variables• type of variable can change- remember the shoot in the foot part !• enforced type casting to validate types

Confused yet ?

Page 33: Php Crash Course - Macq Electronique 2010

Type Juggling example<?php$foo = "0"; // $foo is string (ASCII 48)$foo += 2; // $foo is now an integer (2)$foo = $foo + 1.3; // $foo is now a float (3.3)$foo = 5 + "10 Little Piggies"; // $foo is integer (15)$foo = 5 + "20 Small Pigs"; // $foo is integer (25)?>

Page 34: Php Crash Course - Macq Electronique 2010

Variables

• Basics• Predefined variables• Variable scope• Variable variables

Page 35: Php Crash Course - Macq Electronique 2010

Basics<?php

$var = 'Bob';$Var = 'Joe';echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number$_4site = 'not yet'; // valid; starts with an underscore$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.

Page 36: Php Crash Course - Macq Electronique 2010

Basics in PHP 6

Page 37: Php Crash Course - Macq Electronique 2010

Predefined Variables• Superglobals: are built-in variables (always available in all scopes)• $GLOBALS: References all variables available in global scope• $_SERVER: Server and execution environment information• $_GET: HTTP GET variables• $_POST: HTTP POST variables• $_FILES: HTTP File Upload variables• $_REQUEST: HTTP Request variables• $_SESSION: Session variables• $_ENV: Environment variables• $_COOKIE: HTTP Cookies• $php_errormsg: The previous error message• $HTTP_RAW_POST_DATA: Raw POST data• $http_response_header: HTTP response headers• $argc: The number of arguments passed to script• $argv: Array of arguments passed to script

Page 38: Php Crash Course - Macq Electronique 2010

Variable Scopecontext in which a variable is defined<?php$a = 1;include ‘file.inc.php’; // $a is known inside the included script

global scope<?php

$a = 1;$b = 2;

function foo(){ global $a, $b; echo $b = $a + $b;}

foo(); // outputs 3echo $b; // outputs 3 ($b is known outside it’s scope)

Page 39: Php Crash Course - Macq Electronique 2010

Variable Variables<?php

$a = ‘php’; // value ‘php’ stored in $a

$$a = ‘rules’; // value ‘rules’ stored in $$a (or $php)

echo “$a ${$a}”; // outputs ‘php rules’

echo “$a $php”; // outputs ‘php rules’

Page 40: Php Crash Course - Macq Electronique 2010

Constants

• an identifier (name) for a simple value• that value cannot change• is case-sensitive by default• are always uppercase (by convention)• 2 types- basic- magic

Page 41: Php Crash Course - Macq Electronique 2010

Basic Constants<?php

define(‘CONSTANT’, ‘value’);define(‘KEY_ELEMENT’, 1);define(‘SYNTAX_CHECK’, true);

echo CONSTANT // outputs ‘value’echo Constant // outputs ‘Constant’ and issues a notice

As of PHP 5.3const CONSTANT = ‘value’;

echo CONSTANT; // ouputs ‘value’

Page 42: Php Crash Course - Macq Electronique 2010

Magic Constants

• __LINE__: current line number of the file• __FILE__: full path and filename of the file• __DIR__: directory of the file

• __FUNCTION__: function name (cs)• __CLASS__: class name (cs)• __METHOD__: class method name (cs)

• __NAMESPACE__: current namespace (cs)

Page 43: Php Crash Course - Macq Electronique 2010

Expressions$a = 5;

function foo(){ return ‘bar’;}

0 < $a ? true : false;

$a = $b = 2; // both $a and $b have a value of 2$c = ++$b; // $c has value 3 and $b has value 3$d = $c++; // $d has value 3 and $c has value 4

Page 44: Php Crash Course - Macq Electronique 2010

Operators

• Operator Precedence• Arithmetic Operators• Assignment Operators• Bitwise Operators• Comparison Operators• Error Control Operators• Execution Operators• Incrementing/Decrementing Operators• Logical Operators• String Operators• Array Operators• Type Operators

Page 45: Php Crash Course - Macq Electronique 2010

Control structures

• if• else• elseif/else if• while• do-while• for• foreach• break• continue• switch

• declare• return• require• include• require_once• include_once• goto

Page 46: Php Crash Course - Macq Electronique 2010

Functions<?php function a($n){ b($n); return ($n * $n); }

function b(&$n){ $n++; }

echo a(5); //Outputs 36

Page 47: Php Crash Course - Macq Electronique 2010

Next step: advanced PHP

Classes and ObjectsAbstraction

SecurityPHP Hidden Gems

Page 48: Php Crash Course - Macq Electronique 2010

LengstorfPHP

Companion eBook

Available

this print for content only—size & color not accurate

BOOKS FOR PROFESSIONALS BY PROFESSIONALS®

CYAN MAGENTA

YELLOW BLACK

PHP for Absolute BeginnersDear Reader,

PHP for Absolute Beginners will take you from zero to full-speed with PHP pro-gramming in an easy-to-understand, practical manner. Rather than building applications with no real-world use, this book teaches you PHP by walking you through the development of a blogging web site.

You’ll start by creating a simple web-ready blog, then you'll learn how to add password-protected controls, support for multiple pages, the ability to upload and resize images, a user comment system, and finally, how to integrate with sites like Twitter.

Along the way, you'll also learn a few advanced tricks including creating friendly URLs with .htaccess, using regular expressions, object-oriented pro-gramming, and more.

I wrote this book to help you make the leap to PHP developer in hopes that you can put your valuable skills to work for your company, your clients, or on your own personal blog. The concepts in this book will leave you ready to take on the challenges of the new online world, all while having fun!

Jason Lengstorf

THE APRESS ROADMAP

PHP Objects, Patterns, and Practice

Practical Web 2.0 Applications with PHP

Beginning Ajax and PHP

Pro PHP: Patterns, Frameworks,

Testing, and More

PHP for Absolute Beginners

Beginning PHP and MySQL

US $34.99

Shelve in: PHP

User level: Beginner

www.apress.comSOURCE CODE ONLINE

Companion eBook

See last page for details

on $10 eBook version

trim = 7.5" x 9.25" spine = 0.75" 408 page count

THE EXPERT’S VOICE® IN OPEN SOURCE

PHP for Absolute Beginners

Jason Lengstorf

Everything you need to know to get started with PHP

for Absolute Beginners

Recommended Reading

PHP for Absolute BeginnersApressJason Lengstorf

Page 49: Php Crash Course - Macq Electronique 2010

CreditsBall of nails - Count Rushmore

http://flickr.com/photos/countrushmore/2437899191

Life is too short for Java - Terry Chayhttp://flickr.com/photos/tychay/1388234558

Ruby Fails - IBSpoof (stickers by @spooons)http://www.flickr.com/photos/ibspoof/2879088241

Monkey Face - Mr Pinshttp://flickr.com/photos/7359188@N02/1358576877

Unicode Identifiers - Andrei Zmievski / Andrew Magerhttp://andrewmager.com/geeksessions-13-php-scalability-and-performance/

Confused - Kristian D.http://flickr.com/photos/kristiand/3223044657

Page 50: Php Crash Course - Macq Electronique 2010

Questions ?

Slides on SlideSharehttp://www.slideshare.net/DragonBe

Give feedback !http://joind.in/1256