SlideShare una empresa de Scribd logo
1 de 78
Intermediate PHP
Bradley Holt & Matthew Weier O’Phinney
Arrays




Photo by AJ Cann
Associate values to keys

Keys can be integers (enumerative arrays) or
strings (associative arrays)

Values can be primitive types, objects, or
other arrays (multidimensional arrays)
<?php
$post = array(
   'id'           => 1234,
   'title'        => 'Intermediate PHP',
   'updated'      => new DateTime(
      '2010-12-16T18:00:00-05:00'
   ),
   'draft'        => false,
   'priority'     => 0.8,
   'categories' => array('PHP', 'BTV')
);
Reading, Writing, and
 Appending Arrays
<?php
$post = array(
   'id'         => 1234,
   'title'      => 'Intermediate PHP',
   // …
);
echo $post['title']; // Intermediate PHP
<?php
$post = array(
   'id'         => 1234,
   'title'      => 'Intermediate PHP',
   // …
);
$post['title'] = 'PHP 201';
<?php
$post = array(
   'id'           => 1234,
   'title'        => 'Intermediate PHP',
   'updated'      => new DateTime(
      '2010-12-16T18:00:00-05:00'
   ),
   'draft'        => false,
   'priority'     => 0.8,
   'categories' => array('PHP', 'BTV')
);
$post['summary'] = 'Arrays, functions, and
objects';
<?php
$post = array(
   // …
   'categories' => array('PHP', 'BTV')
);
$post['categories'][] = 'Programming';
print_r($post['categories']);
/*
Array
(
     [0] => PHP
     [1] => BTV
     [2] => Programming
)
  */
<?php
$post = array(
   // …
   'categories' => array('PHP', 'BTV')
);
$post['categories'][1] = 'Burlington';
print_r($post['categories']);
/*
Array
(
     [0] => PHP
     [1] => Burlington
)
  */
Iterating Over Arrays
<?php
$post = array(
   // …
   'categories' => array('PHP', 'BTV')
);
foreach ($post['categories'] as $v) {
   echo $v . PHP_EOL;
}
/*
PHP
BTV
  */
<?php
$post = array(
   // …
   'categories' => array('PHP', 'BTV')
);
foreach ($post['categories'] as $k => $v) {
   echo $k . ': ' . $v . PHP_EOL;
}
/*
0: PHP
1: BTV
  */
<?php
$post = array(
   'id'          => 1234,
   'title'       => 'Intermediate PHP',
   // …
);
foreach ($post as $k => $v) {
   echo $k . ': ' . $v . PHP_EOL;
}
/*
id: 1234
title: Intermediate PHP
…
  */
Implode and Explode
<?php
$post = array(
   // …
   'categories' => array('PHP', 'BTV')
);
echo implode(', ', $post['categories']);
// PHP, BTV
<?php
$post = array(
   // …
   'categories' =>
     explode(', ', 'PHP, BTV')
);
print_r($post['categories']);
/*
Array
(
     [0] => PHP
     [1] => BTV
)
  */
Array Key Exists,
In Array, and Array Keys
<?php
$post = array(
   'id'          => 1234,
   // …
   'categories' => array('PHP', 'BTV')
);
if (array_key_exists('categories', $post))
{
   echo implode(', ', $post['categories']);
} else {
   echo 'Uncategorized';
}
<?php
$post = array(
   // …
   'categories' => array('PHP', 'BTV')
);
if (in_array('PHP', $post['categories'])) {
     echo 'PHP: Hypertext Preprocessor';
}
<?php
$posts = array(
   1233 => array(/* … */),
   1234 => array(/* … */),
);
print_r(array_keys($posts));
/*
Array
(
     [0] => 1233
     [1] => 1234
)
  */
Sorting Arrays
<?php
$post = array(
   // …
   'categories' => array('PHP', 'BTV')
);
sort($post['categories']);
print_r($post['categories']);
/*
Array
(
     [0] => BTV
     [1] => PHP
)
  */
Sorting Function
          Attributes
Some sort by value, others by key

Some maintain key association, others do not

Some sort low to high, others high to low

Some are case sensitive, some are not

See:
http://www.php.net/manual/en/array.sorting.php
Sorting Functions
array_multisort()   rsort()

asort()             shuffle()

arsort()            sort()

krsort()            uasort()

ksort()             uksort()

natcasesort()       usort()

natsort()
Stacks and Queues




Photo by Phil Cooper   Photo by Thomas W
Array Push and
Array Pop (stack)
<?php
$post = array(
   // …
   'categories' => array('PHP')
);
array_push($post['categories'], 'BTV');
echo array_pop($post['categories']);
// BTV
print_r($post['categories']);
/*
Array
(
     [0] => PHP
)
  */
Array Unshift and
Array Pop (queue)
<?php
$post = array(
   // …
   'categories' => array('BTV')
);
array_unshift($post['categories'], 'PHP');
print_r($post['categories']);
/*
Array
(
     [0] => PHP
     [1] => BTV
)
  */
echo array_pop($post['categories']);
// BTV
Functions
Internal Functions
<?php
print_r(get_defined_functions());
/*
Array
(
     [internal] => Array
         (
             [0] => zend_version
             [1] => func_num_args
             // …
         )
     [user] => Array
         (
         )
)
  */
<?php
$functions = get_defined_functions();
echo count($functions['internal']);
// 1857
<?php
$name = 'Marcus Börger';
if (function_exists('mb_strtolower')) {
  echo mb_strtolower($name, 'UTF-8');
  // marcus börger
} else {
  echo strtolower($name);
  // marcus b?rger
}
User-Defined Functions
Rules

Any valid PHP code is allowed inside
functions, including other functions and class
definitions

Function names are case-insensitive

Once defined, a function cannot be undefined
<?php
function nextId($posts)
{
   return max(array_keys($posts)) + 1;
}
$posts = array(
   1233 => array(/* … */),
   1234 => array(/* … */),
);
echo nextId($posts); // 1235
Type Hinting
<?php
function nextId(array $posts)
{
   return max(array_keys($posts)) + 1;
}
$posts = array(
   1233 => array(/* … */),
   1234 => array(/* … */),
);
echo nextId($posts); // 1235
echo nextId(1234);
// Argument 1 passed to nextId() must be an
array, integer given
Multiple Arguments
<?php
function isPublished(DateTime $published,
$draft)
{
  if ($draft) { return false; }
  $now = new DateTime();
  return $now >= $published;
}
$published = new
DateTime('2010-12-16T18:00:00-05:00');
$draft = false;
var_dump(isPublished($published, $draft));
// bool(true)
Default Arguments
<?php
function isPublished(DateTime $published,
$draft, $now = false)
{
  if ($draft) { return false; }
  $now = $now ? $now : new DateTime();
  return $now >= $published;
}
$published = new
DateTime('2010-12-16T18:00:00-05:00');
$draft = false;
$now = new
DateTime('2010-12-16T17:59:59-05:00');
var_dump(isPublished($published, $draft,
$now));
// bool(false)
Function Overloading
     (not really)
<?php
function nextId($arg1)
{
   switch (true) {
     case is_array($arg1):
       return max(array_keys($arg1)) + 1;
     case is_int($arg1):
       return $arg1 + 1;
   }
}
$posts = array(
   1233 => array(/* … */),
   1234 => array(/* … */),
);
echo nextId($posts); // 1235
echo nextId(1234); // 1235
Variable Number of
    Arguments
<?php
function mostRecent()
{
   $max = false;
   foreach (func_get_args() as $arg) {
     $max = $arg > $max ? $arg : $max;
   }
   return $max;
}
$mostRecent = mostRecent(
     new DateTime('2010-12-14T18:00:00'),
     new DateTime('2010-12-16T18:00:00'),
     new DateTime('2010-12-15T18:00:00')
);
// 2010-12-16T18:00:00
Objects
Basics


Encapsulate metadata and behavior

metadata => properties (variables, constants)

behavior => methods (functions)
Anonymous Objects
Cast an Associative
        Array to (object)
<?php
$a = array(
   'foo' => 'bar',
);
$o = (object) $a;
echo $o->foo; // 'bar'
stdClass


$o = new stdClass;
$o->foo = 'bar';
echo $o->foo; // 'bar'
Declaring a Class

<?php
class Foo
{
}
Declaring Properties

<?php
class Foo
{
  protected $bar = 'bar';
}
Extending Classes

<?php
class FooBar extends Foo
{
}
Visibility
public: accessible from instances or within
methods of any visibility, and within
extending classes

protected: accessible only within instance
methods of any visibility, and within
extending classes

private: accessible only within instance
methods from the declaring class
Modifiers


final: cannot be overridden in extending
classes

abstract: must be overridden in extending
classes
Abstract Classes
<?php
abstract class AbstractFoo
{
  abstract public function sayBar();
}

class Foo extends AbstractFoo
{
  public $bar;

    public function sayBar()
    {
      echo $this->bar;
    }
}
Interfaces
"Blueprints" for classes

Typically indicate behaviors found in
implementing classes

You can implement many interfaces, but only
extend once

  Allows you to compose multiple behaviors
  into a single class
<?php
interface Resource {
  public function getResource();
}
interface Dispatcher {
  public function dispatch();
}

abstract class DispatchableResource
implements Resource,Dispatcher
{
  // …
}
<?php
interface Resource { /* … */ }
interface Dispatcher { /* … */ }

abstract class DispatchableResource
implements Resource,Dispatcher
{
  protected $resource;
  public function getResource() {
    return $this->resource;
  }
  public function dispatch() {
    return 'Dispatched ' . $this-
>getResource();
  }
}
<?php
interface Resource { /* … */ }
interface Dispatcher { /* … */ }

abstract class DispatchableResource
implements Resource,Dispatcher { /* … */ }

class TrafficCop extends
DispatchableResource
{
  protected $resource = 'traffic cop';
}
$cop = new TrafficCop();
echo $cop->dispatch();
// 'Dispatched traffic cop'
Useful Tidbits
Type hinting: you can indicate an interface, abstract
   class, or class name "hint" with parameters:

 public function doSomething(Dispatcher
 $dispatcher) {/* … */}


                  Test for types:

 if ($object instanceof Dispatcher) { }


  Type hints look at the entire inheritance chain,
                including interfaces!
Statics
Static properties and methods may be
accessed without instantiation

Requires a different token to access:

  ClassName::$varName for variables

  Classname::methodName() for methods

  or use self or parent or static within
  a class, instead of the class name
Late Static Binding



static is used for "Late Static
Binding" (LSB)
<?php
class BasicPerson
{
  public static $sex = 'unisex';
  public static function getSex()
  {
    return static::$sex;
  }
}
class MalePerson extends BasicPerson
{
  public static $sex = 'male'; // LSB
}
echo BasicPerson::getSex(); // 'unisex'
BasicPerson::$sex = 'female';
echo BasicPerson::getSex(); // 'female'
echo MalePerson::getSex(); // 'male'
Magic Methods
Tie into different states of an object
Construct, Destruct, and
        Invoke
 __construct — Constructor (used when
 "new Class" is called)

 __destruct — Destructor (called when
 object is destroyed)

 __invoke — Call an object instance like a
 function (echo $object();)
Sleep and Wakeup


__sleep — Define what properties should be
serialized, and how

__wakeup — Determine how to initialize state
from serialized instance
Call and Call Static


Overload method access

__call

__callStatic
Get and Set


Overload property access

__get

__set
Cardinal Rule



Objects should model discrete concepts, and
not just be a container for functions.
Questions?
Thank You
Bradley Holt & Matthew Weier O’Phinney
License
Intermediate PHP is licensed under a Creative
Commons Attribution-NonCommercial-ShareAlike
3.0 Unported License.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
php basics
php basicsphp basics
php basics
 
PHP Tips for certification - OdW13
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Using PHP
Using PHPUsing PHP
Using PHP
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Web technology html5 php_mysql
Web technology html5 php_mysqlWeb technology html5 php_mysql
Web technology html5 php_mysql
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
Php string function
Php string function Php string function
Php string function
 
Php
PhpPhp
Php
 
Dev traning 2016 basics of PHP
Dev traning 2016   basics of PHPDev traning 2016   basics of PHP
Dev traning 2016 basics of PHP
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
PHP: The easiest language to learn.
PHP: The easiest language to learn.PHP: The easiest language to learn.
PHP: The easiest language to learn.
 

Destacado

Appendex e
Appendex eAppendex e
Appendex eswavicky
 
Appendex d
Appendex dAppendex d
Appendex dswavicky
 
Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Chhom Karath
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPprabhatjon
 
LiDAR Aided Decision Making
LiDAR Aided Decision MakingLiDAR Aided Decision Making
LiDAR Aided Decision MakingLidar Blog
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)Chhom Karath
 
Drought: Looking Back and Planning Ahead, Todd Votteler
Drought: Looking Back and Planning Ahead, Todd VottelerDrought: Looking Back and Planning Ahead, Todd Votteler
Drought: Looking Back and Planning Ahead, Todd VottelerTXGroundwaterSummit
 
Chapter 7 Multimedia
Chapter 7 MultimediaChapter 7 Multimedia
Chapter 7 MultimediaPatty Ramsey
 
Survey Grade LiDAR Technologies for Transportation Engineering
Survey Grade LiDAR Technologies for Transportation EngineeringSurvey Grade LiDAR Technologies for Transportation Engineering
Survey Grade LiDAR Technologies for Transportation EngineeringQuantum Spatial
 
300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles Porter300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles PorterTXGroundwaterSummit
 
Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...Pedro Llorens
 
Appendex f
Appendex fAppendex f
Appendex fswavicky
 
Appendex a
Appendex aAppendex a
Appendex aswavicky
 
Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)Chhom Karath
 
Final morris esri_nwgis_lidar
Final morris esri_nwgis_lidarFinal morris esri_nwgis_lidar
Final morris esri_nwgis_lidarEric Morris
 
Setting up a gmail account
Setting up a gmail accountSetting up a gmail account
Setting up a gmail accountkeelyswitzer
 
Aquifer Storage and Recovery, Kelley Neumann
Aquifer Storage and Recovery, Kelley NeumannAquifer Storage and Recovery, Kelley Neumann
Aquifer Storage and Recovery, Kelley NeumannTXGroundwaterSummit
 
CIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to ComputersCIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to ComputersPatty Ramsey
 

Destacado (20)

Appendex e
Appendex eAppendex e
Appendex e
 
Appendex d
Appendex dAppendex d
Appendex d
 
Emoji International Name Finder
Emoji International Name FinderEmoji International Name Finder
Emoji International Name Finder
 
Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
LiDAR Aided Decision Making
LiDAR Aided Decision MakingLiDAR Aided Decision Making
LiDAR Aided Decision Making
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)
 
Drought: Looking Back and Planning Ahead, Todd Votteler
Drought: Looking Back and Planning Ahead, Todd VottelerDrought: Looking Back and Planning Ahead, Todd Votteler
Drought: Looking Back and Planning Ahead, Todd Votteler
 
Chapter 7 Multimedia
Chapter 7 MultimediaChapter 7 Multimedia
Chapter 7 Multimedia
 
Survey Grade LiDAR Technologies for Transportation Engineering
Survey Grade LiDAR Technologies for Transportation EngineeringSurvey Grade LiDAR Technologies for Transportation Engineering
Survey Grade LiDAR Technologies for Transportation Engineering
 
300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles Porter300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles Porter
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...
 
Appendex f
Appendex fAppendex f
Appendex f
 
Appendex a
Appendex aAppendex a
Appendex a
 
Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)
 
Final morris esri_nwgis_lidar
Final morris esri_nwgis_lidarFinal morris esri_nwgis_lidar
Final morris esri_nwgis_lidar
 
Setting up a gmail account
Setting up a gmail accountSetting up a gmail account
Setting up a gmail account
 
Aquifer Storage and Recovery, Kelley Neumann
Aquifer Storage and Recovery, Kelley NeumannAquifer Storage and Recovery, Kelley Neumann
Aquifer Storage and Recovery, Kelley Neumann
 
CIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to ComputersCIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to Computers
 

Similar a Intermediate PHP

SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Ajay Khatri
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHPHari K T
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceIvan Chepurnyi
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netProgrammer Blog
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 

Similar a Intermediate PHP (20)

php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Oops in php
Oops in phpOops in php
Oops in php
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 

Más de Bradley Holt

Domain-Driven Design at ZendCon 2012
Domain-Driven Design at ZendCon 2012Domain-Driven Design at ZendCon 2012
Domain-Driven Design at ZendCon 2012Bradley Holt
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven DesignBradley Holt
 
Entity Relationships in a Document Database at CouchConf Boston
Entity Relationships in a Document Database at CouchConf BostonEntity Relationships in a Document Database at CouchConf Boston
Entity Relationships in a Document Database at CouchConf BostonBradley Holt
 
CouchConf NYC CouchApps
CouchConf NYC CouchAppsCouchConf NYC CouchApps
CouchConf NYC CouchAppsBradley Holt
 
ZendCon 2011 UnCon Domain-Driven Design
ZendCon 2011 UnCon Domain-Driven DesignZendCon 2011 UnCon Domain-Driven Design
ZendCon 2011 UnCon Domain-Driven DesignBradley Holt
 
ZendCon 2011 Learning CouchDB
ZendCon 2011 Learning CouchDBZendCon 2011 Learning CouchDB
ZendCon 2011 Learning CouchDBBradley Holt
 
jQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchAppsjQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchAppsBradley Holt
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchAppsBradley Holt
 
OSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBOSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBBradley Holt
 
Load Balancing with Apache
Load Balancing with ApacheLoad Balancing with Apache
Load Balancing with ApacheBradley Holt
 
CouchDB at New York PHP
CouchDB at New York PHPCouchDB at New York PHP
CouchDB at New York PHPBradley Holt
 
New Features in PHP 5.3
New Features in PHP 5.3New Features in PHP 5.3
New Features in PHP 5.3Bradley Holt
 
Resource-Oriented Web Services
Resource-Oriented Web ServicesResource-Oriented Web Services
Resource-Oriented Web ServicesBradley Holt
 
Zend Framework Quick Start Walkthrough
Zend Framework Quick Start WalkthroughZend Framework Quick Start Walkthrough
Zend Framework Quick Start WalkthroughBradley Holt
 
Burlington, VT PHP Users Group Subversion Presentation
Burlington, VT PHP Users Group Subversion PresentationBurlington, VT PHP Users Group Subversion Presentation
Burlington, VT PHP Users Group Subversion PresentationBradley Holt
 

Más de Bradley Holt (15)

Domain-Driven Design at ZendCon 2012
Domain-Driven Design at ZendCon 2012Domain-Driven Design at ZendCon 2012
Domain-Driven Design at ZendCon 2012
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven Design
 
Entity Relationships in a Document Database at CouchConf Boston
Entity Relationships in a Document Database at CouchConf BostonEntity Relationships in a Document Database at CouchConf Boston
Entity Relationships in a Document Database at CouchConf Boston
 
CouchConf NYC CouchApps
CouchConf NYC CouchAppsCouchConf NYC CouchApps
CouchConf NYC CouchApps
 
ZendCon 2011 UnCon Domain-Driven Design
ZendCon 2011 UnCon Domain-Driven DesignZendCon 2011 UnCon Domain-Driven Design
ZendCon 2011 UnCon Domain-Driven Design
 
ZendCon 2011 Learning CouchDB
ZendCon 2011 Learning CouchDBZendCon 2011 Learning CouchDB
ZendCon 2011 Learning CouchDB
 
jQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchAppsjQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchApps
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchApps
 
OSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBOSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDB
 
Load Balancing with Apache
Load Balancing with ApacheLoad Balancing with Apache
Load Balancing with Apache
 
CouchDB at New York PHP
CouchDB at New York PHPCouchDB at New York PHP
CouchDB at New York PHP
 
New Features in PHP 5.3
New Features in PHP 5.3New Features in PHP 5.3
New Features in PHP 5.3
 
Resource-Oriented Web Services
Resource-Oriented Web ServicesResource-Oriented Web Services
Resource-Oriented Web Services
 
Zend Framework Quick Start Walkthrough
Zend Framework Quick Start WalkthroughZend Framework Quick Start Walkthrough
Zend Framework Quick Start Walkthrough
 
Burlington, VT PHP Users Group Subversion Presentation
Burlington, VT PHP Users Group Subversion PresentationBurlington, VT PHP Users Group Subversion Presentation
Burlington, VT PHP Users Group Subversion Presentation
 

Último

So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 

Último (20)

So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 

Intermediate PHP

  • 1. Intermediate PHP Bradley Holt & Matthew Weier O’Phinney
  • 3. Associate values to keys Keys can be integers (enumerative arrays) or strings (associative arrays) Values can be primitive types, objects, or other arrays (multidimensional arrays)
  • 4. <?php $post = array( 'id' => 1234, 'title' => 'Intermediate PHP', 'updated' => new DateTime( '2010-12-16T18:00:00-05:00' ), 'draft' => false, 'priority' => 0.8, 'categories' => array('PHP', 'BTV') );
  • 5. Reading, Writing, and Appending Arrays
  • 6. <?php $post = array( 'id' => 1234, 'title' => 'Intermediate PHP', // … ); echo $post['title']; // Intermediate PHP
  • 7. <?php $post = array( 'id' => 1234, 'title' => 'Intermediate PHP', // … ); $post['title'] = 'PHP 201';
  • 8. <?php $post = array( 'id' => 1234, 'title' => 'Intermediate PHP', 'updated' => new DateTime( '2010-12-16T18:00:00-05:00' ), 'draft' => false, 'priority' => 0.8, 'categories' => array('PHP', 'BTV') ); $post['summary'] = 'Arrays, functions, and objects';
  • 9. <?php $post = array( // … 'categories' => array('PHP', 'BTV') ); $post['categories'][] = 'Programming'; print_r($post['categories']); /* Array ( [0] => PHP [1] => BTV [2] => Programming ) */
  • 10. <?php $post = array( // … 'categories' => array('PHP', 'BTV') ); $post['categories'][1] = 'Burlington'; print_r($post['categories']); /* Array ( [0] => PHP [1] => Burlington ) */
  • 12. <?php $post = array( // … 'categories' => array('PHP', 'BTV') ); foreach ($post['categories'] as $v) { echo $v . PHP_EOL; } /* PHP BTV */
  • 13. <?php $post = array( // … 'categories' => array('PHP', 'BTV') ); foreach ($post['categories'] as $k => $v) { echo $k . ': ' . $v . PHP_EOL; } /* 0: PHP 1: BTV */
  • 14. <?php $post = array( 'id' => 1234, 'title' => 'Intermediate PHP', // … ); foreach ($post as $k => $v) { echo $k . ': ' . $v . PHP_EOL; } /* id: 1234 title: Intermediate PHP … */
  • 16. <?php $post = array( // … 'categories' => array('PHP', 'BTV') ); echo implode(', ', $post['categories']); // PHP, BTV
  • 17. <?php $post = array( // … 'categories' => explode(', ', 'PHP, BTV') ); print_r($post['categories']); /* Array ( [0] => PHP [1] => BTV ) */
  • 18. Array Key Exists, In Array, and Array Keys
  • 19. <?php $post = array( 'id' => 1234, // … 'categories' => array('PHP', 'BTV') ); if (array_key_exists('categories', $post)) { echo implode(', ', $post['categories']); } else { echo 'Uncategorized'; }
  • 20. <?php $post = array( // … 'categories' => array('PHP', 'BTV') ); if (in_array('PHP', $post['categories'])) { echo 'PHP: Hypertext Preprocessor'; }
  • 21. <?php $posts = array( 1233 => array(/* … */), 1234 => array(/* … */), ); print_r(array_keys($posts)); /* Array ( [0] => 1233 [1] => 1234 ) */
  • 23. <?php $post = array( // … 'categories' => array('PHP', 'BTV') ); sort($post['categories']); print_r($post['categories']); /* Array ( [0] => BTV [1] => PHP ) */
  • 24. Sorting Function Attributes Some sort by value, others by key Some maintain key association, others do not Some sort low to high, others high to low Some are case sensitive, some are not See: http://www.php.net/manual/en/array.sorting.php
  • 25. Sorting Functions array_multisort() rsort() asort() shuffle() arsort() sort() krsort() uasort() ksort() uksort() natcasesort() usort() natsort()
  • 26. Stacks and Queues Photo by Phil Cooper Photo by Thomas W
  • 27. Array Push and Array Pop (stack)
  • 28. <?php $post = array( // … 'categories' => array('PHP') ); array_push($post['categories'], 'BTV'); echo array_pop($post['categories']); // BTV print_r($post['categories']); /* Array ( [0] => PHP ) */
  • 29. Array Unshift and Array Pop (queue)
  • 30. <?php $post = array( // … 'categories' => array('BTV') ); array_unshift($post['categories'], 'PHP'); print_r($post['categories']); /* Array ( [0] => PHP [1] => BTV ) */ echo array_pop($post['categories']); // BTV
  • 33. <?php print_r(get_defined_functions()); /* Array ( [internal] => Array ( [0] => zend_version [1] => func_num_args // … ) [user] => Array ( ) ) */
  • 34. <?php $functions = get_defined_functions(); echo count($functions['internal']); // 1857
  • 35. <?php $name = 'Marcus Börger'; if (function_exists('mb_strtolower')) { echo mb_strtolower($name, 'UTF-8'); // marcus börger } else { echo strtolower($name); // marcus b?rger }
  • 37. Rules Any valid PHP code is allowed inside functions, including other functions and class definitions Function names are case-insensitive Once defined, a function cannot be undefined
  • 38. <?php function nextId($posts) { return max(array_keys($posts)) + 1; } $posts = array( 1233 => array(/* … */), 1234 => array(/* … */), ); echo nextId($posts); // 1235
  • 40. <?php function nextId(array $posts) { return max(array_keys($posts)) + 1; } $posts = array( 1233 => array(/* … */), 1234 => array(/* … */), ); echo nextId($posts); // 1235 echo nextId(1234); // Argument 1 passed to nextId() must be an array, integer given
  • 42. <?php function isPublished(DateTime $published, $draft) { if ($draft) { return false; } $now = new DateTime(); return $now >= $published; } $published = new DateTime('2010-12-16T18:00:00-05:00'); $draft = false; var_dump(isPublished($published, $draft)); // bool(true)
  • 44. <?php function isPublished(DateTime $published, $draft, $now = false) { if ($draft) { return false; } $now = $now ? $now : new DateTime(); return $now >= $published; } $published = new DateTime('2010-12-16T18:00:00-05:00'); $draft = false; $now = new DateTime('2010-12-16T17:59:59-05:00'); var_dump(isPublished($published, $draft, $now)); // bool(false)
  • 45. Function Overloading (not really)
  • 46. <?php function nextId($arg1) { switch (true) { case is_array($arg1): return max(array_keys($arg1)) + 1; case is_int($arg1): return $arg1 + 1; } } $posts = array( 1233 => array(/* … */), 1234 => array(/* … */), ); echo nextId($posts); // 1235 echo nextId(1234); // 1235
  • 47. Variable Number of Arguments
  • 48. <?php function mostRecent() { $max = false; foreach (func_get_args() as $arg) { $max = $arg > $max ? $arg : $max; } return $max; } $mostRecent = mostRecent( new DateTime('2010-12-14T18:00:00'), new DateTime('2010-12-16T18:00:00'), new DateTime('2010-12-15T18:00:00') ); // 2010-12-16T18:00:00
  • 50. Basics Encapsulate metadata and behavior metadata => properties (variables, constants) behavior => methods (functions)
  • 52. Cast an Associative Array to (object) <?php $a = array( 'foo' => 'bar', ); $o = (object) $a; echo $o->foo; // 'bar'
  • 53. stdClass $o = new stdClass; $o->foo = 'bar'; echo $o->foo; // 'bar'
  • 55. Declaring Properties <?php class Foo { protected $bar = 'bar'; }
  • 57. Visibility public: accessible from instances or within methods of any visibility, and within extending classes protected: accessible only within instance methods of any visibility, and within extending classes private: accessible only within instance methods from the declaring class
  • 58. Modifiers final: cannot be overridden in extending classes abstract: must be overridden in extending classes
  • 60. <?php abstract class AbstractFoo { abstract public function sayBar(); } class Foo extends AbstractFoo { public $bar; public function sayBar() { echo $this->bar; } }
  • 61. Interfaces "Blueprints" for classes Typically indicate behaviors found in implementing classes You can implement many interfaces, but only extend once Allows you to compose multiple behaviors into a single class
  • 62. <?php interface Resource { public function getResource(); } interface Dispatcher { public function dispatch(); } abstract class DispatchableResource implements Resource,Dispatcher { // … }
  • 63. <?php interface Resource { /* … */ } interface Dispatcher { /* … */ } abstract class DispatchableResource implements Resource,Dispatcher { protected $resource; public function getResource() { return $this->resource; } public function dispatch() { return 'Dispatched ' . $this- >getResource(); } }
  • 64. <?php interface Resource { /* … */ } interface Dispatcher { /* … */ } abstract class DispatchableResource implements Resource,Dispatcher { /* … */ } class TrafficCop extends DispatchableResource { protected $resource = 'traffic cop'; } $cop = new TrafficCop(); echo $cop->dispatch(); // 'Dispatched traffic cop'
  • 66. Type hinting: you can indicate an interface, abstract class, or class name "hint" with parameters: public function doSomething(Dispatcher $dispatcher) {/* … */} Test for types: if ($object instanceof Dispatcher) { } Type hints look at the entire inheritance chain, including interfaces!
  • 67. Statics Static properties and methods may be accessed without instantiation Requires a different token to access: ClassName::$varName for variables Classname::methodName() for methods or use self or parent or static within a class, instead of the class name
  • 68. Late Static Binding static is used for "Late Static Binding" (LSB)
  • 69. <?php class BasicPerson { public static $sex = 'unisex'; public static function getSex() { return static::$sex; } } class MalePerson extends BasicPerson { public static $sex = 'male'; // LSB } echo BasicPerson::getSex(); // 'unisex' BasicPerson::$sex = 'female'; echo BasicPerson::getSex(); // 'female' echo MalePerson::getSex(); // 'male'
  • 70. Magic Methods Tie into different states of an object
  • 71. Construct, Destruct, and Invoke __construct — Constructor (used when "new Class" is called) __destruct — Destructor (called when object is destroyed) __invoke — Call an object instance like a function (echo $object();)
  • 72. Sleep and Wakeup __sleep — Define what properties should be serialized, and how __wakeup — Determine how to initialize state from serialized instance
  • 73. Call and Call Static Overload method access __call __callStatic
  • 74. Get and Set Overload property access __get __set
  • 75. Cardinal Rule Objects should model discrete concepts, and not just be a container for functions.
  • 77. Thank You Bradley Holt & Matthew Weier O’Phinney
  • 78. License Intermediate PHP is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. Reading from an associative array\n
  7. Writing to an associative array\n
  8. Appending to an associative array\n
  9. Appending to an enumerative array\n
  10. Writing to an enumerative array\n
  11. \n
  12. Iterating values in an enumerative array\n
  13. Iterating key value pairs in an enumerative array\n
  14. Iterating key value pairs in an associative array\n
  15. \n
  16. Implode returns a string, not an array.\n
  17. Explode returns an array.\n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. The SPL in PHP 5.3 has new data structures that can make stacks and queues more performant and memory efficient.\n
  27. \n
  28. Example of an array used as a stack (FILO)\n
  29. \n
  30. Example of an array used as a queue (FIFO)\n
  31. \n
  32. \n
  33. \n
  34. The number of internal functions will depend on which extensions you have installed.\n
  35. The multibyte string (mbstring) extension allows you to safely manipulate multibyte strings (e.g. UTF-8).\n
  36. \n
  37. \n
  38. This function finds the highest array key and adds one.\n
  39. \n
  40. You can type hint on array and class names, but not primitive data types like strings and integers.\n
  41. \n
  42. This function determines if a post is published based on its published date and whether or not it&amp;#x2019;s a draft.\n
  43. \n
  44. This is essentially the same as the previous function but allows you to specific when &amp;#x201C;now&amp;#x201D; is.\n
  45. \n
  46. throw new InvalidArgumentException();\n
  47. \n
  48. \n
  49. \n
  50. We already know about variables and functions now!\n
  51. &quot;Anonymous&quot; as they are not of any specific class; they&apos;re basically equivalent to &quot;bare objects&quot; or &quot;object literals&quot; in JavaScript.\n
  52. \n
  53. \n
  54. \n
  55. Definitions may not use computations or runtime values (other than constants); they must be concrete.\n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. Interfaces can extend other interfaces. Methods in interfaces must be public.\n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. If you want the latter, use namespaces!\n
  76. \n
  77. \n
  78. \n