Académique Documents
Professionnel Documents
Culture Documents
PHP
An Introduction
define(FOO, 'foo');
define(BAR, 'bar');
$value = 'bar';
switch ($value) {
case FOO:
// do something;
break;
case BAR:
// do something else
break;
}
Associative Arrays
$person = array(
'last_name' => "Weier O'Phinney",
'first_name' => "Matthew",
'occupation' => 'PHP Developer',
'gender' => 'Male',
'email' => 'matthew@example,com',
);
Functions
class Person
{
}
Define some common class
member variables
class Person
{
public $firstName;
public $lastName;
public $occupation;
public $gender;
public $email;
}
Some types of class members
Variables
Declared using a visibility
operator and normal variable
naming
Constants
Declared with the const
keyword, and no quotes
Methods
Declared with the function
keyword
define methods, which are
functions inside a class
class Person
{
// ... attributes ...
public function boast()
{
return sprintf('%s %s is a %s',
$this->firstName,
$this->lastName,
$this->occupation
);
}
}
Instance variables!
Use your objects!
echo $matthew->boast();
// Matthew Weier O'Phinney is a PHP Developer
Why bother?
It's good programming
Methods have access to:
Whatever is passed to them
Any class member variables,
constants, or methods (with
respect to visibility)
Use $this-> within a class to
access member variables and
methods (unless statically
declared); use -> when
consuming an instance
Use self:: to access member
constants
What is this visibility stuff?
Note:
using Matthew,
not Person!
$matthew = new Matthew();
echo $matthew->boast();
// Matthew Weier O'Phinney is a PHP Developer,
// and wrote this presentation
Interface
keyword!
interface Animal
{
public function makeNoise();
public function eat($food);
}
Interfaces may extend
other interfaces
interface Collection
extends Countable,
IteratorAggregate
{
}
Collection now
inherits methods
from Countable and
IteratorAggregate
Implementing an interface means
defining the interfaces methods
class Family
extends Order
implements Collection
{
// defined by Countable
public function count() {}
// defined by IteratorAggregate
public function getIterator() {}
}
implements keyword;
this object follows that
contract
Abstract Classes
Magic method:
constructor
STATIC members:
Class members that do not
require an object instance in
order to operate.
Global state (i.e., does not
vary between instances); use
rarely and wisely.
Uses the "Paamayim
Nekudotayim" operator (`::`)
for scope resolution
Static example
The type is small
because I don't want
class Registry you to use statics. :)
{
protected static $values = array();
http://thinkvitamin.com/author/lornajanemitchell/
http://php.net/oop
http://php.net/spl