%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is in utf-8 unicode and under           %
% Creative Commons Noncommercial 3.0 License        %
% http://creativecommons.org/licenses/by-nc-sa/3.0/ %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%
%  to do htmlentities($mixedWords, ENT_NOQUOTES, 'UTF-8')

\documentclass[
    a4paper,
    fontsize=9pt,%Grundschrift 10pt, 11pt, 12pt
    %draft,%zum anzeigen typographischer Fehler + Ausschalten der Grafiken
%     openany,
    DIV30,%DIV20 -> große Textfläche, DIV10 -> kleine Textfläche
    landscape,
    DIVcalc,%optimalen DIV-Wert berechnen
    %twoside,% zweiseitig
    %bigheadings,% Kopfzeilen groß
    %1headlines,% Anzahl Kopfzeilen
    %BCOR1.5cm,%Bindekorrektur
    %liststotoc, % Listen ins Inhaltsverzeichnis
    idxtotoc, % Index mit ins Inhaltsverzeichnis
    bibtotoc,%Bibliographie mit ins Inhaltsverzeichnis
    %bibtotocnumbered,%Bibliographie nummeriert oder nicht
    %liststotocnumbered,
    %titlepage,%  ExtraTitel
    %notitlepage% kein ExtraTitel
    onelinecaption,% Captions wenn einzeilig, dann zantriert, sonst Block
    %noonelinecaption,% Keine Sonderbehandling
    %tablecaptionbelow,
    tablecaptionabove,
    %origlongtable,% KOMA definiert
    %headinclude,%Kopf zum Text dazu
    %headexclude,%Kopf nicht zum Text dazu
    %footinclude,%Fuß zum Text dazu
    %footexclude,%Fuß nicht zum Text dazu
    %mpinclude,%Marginalien zur Textfläche dazu
%     twocolumn,
    mpinclude=false%Marginalien nicht zur Textfläche
    ]{scrartcl}% KOMA book Klasse
\usepackage{nameref}  % refeffing to names
\usepackage{amssymb}
\usepackage{enumitem} % managing margins in itmeize description etc.
%%% vertikal
%  topsep
%  partopsep
%  parsep
%  itemsep
%%% horizontal
%  leftmargin
%  rightmargin
%  listparindent
%  labelwidth
%  labelsep
%  itemindent

\usepackage[utf8]{inputenc}
\usepackage[german,english]{babel} %    !!! alle \figurename \tablename sind jetzt in:
  \addto\captionsgerman{\renewcommand{\figurename} {Abb.}} % umzudefinieren
  \addto\captionsenglish{\renewcommand{\figurename}{Fig.}} % umzudefinieren
  \addto\captionsenglish{\renewcommand{\tablename} {Tab.}} % umzudefinieren
\usepackage[
  babel,
  english=american,%british,
  german=quotes]
  {csquotes} % auto qoutes
\MakeAutoQuote{«}{»}
% \defineshorthand{"`}{\openautoquote}
% \defineshorthand{"'}{\closeautoquote}
%   \usepackage[
%     style=authoryear-comp,
%     sorting=nyt, % name year title
%     hyperref,
%     babel=hyphen,
%     date=short,
%     backref % Literaturliste -> schreibt 'S.: 20'
%     ]
%   {biblatex}% ×
%   \bibliography{/home/plankandreas/Literatur/Literatur-utf8}
%   \bibliography{/home/plankandreas/Documents/Literatur/Literatur-utf8}
% \usepackage[sectionbib]{natbib}      % Autor, Jahr - Zitierung
\usepackage[T1]{fontenc}             % für ü ä ö separates Zeichen kein u + ¨
\usepackage{lmodern}
  \renewcommand*\familydefault{\sfdefault}

\usepackage{bbding}
  %× Icons
    %\HandRight bbding
    \newcommand{\hr}{%
    \raisebox{-0.5ex}{\HandRight~} %
    }%


\usepackage{calc}                    % damit geht z.B. \textwidth-2em
\usepackage{ifthen}
\usepackage[english]{varioref}        % variable Verweise: "Abb. 6 'auf Seite' 14"
\usepackage{xcolor}                  % Farben verbessertes color-Paket
\usepackage{scrtime}                  % Zeit
\usepackage{textcomp} % for listings
\usepackage{listings}
\lstset{% general command to set parameter(s)
  basicstyle=\ttfamily\small, % print whole in small
  keywordstyle=\ttfamily\color{blue},
  identifierstyle=\ttfamily\color{black!60!green!90},% $variables
  commentstyle=\color{white!40!black},
  stringstyle=\color{red!60!green!90!black},
  resetmargins=true,
  xleftmargin=0.0em,
  xrightmargin=0.0em,
  aboveskip=0.1ex,
  belowskip=0.1ex,
  numberstyle=\tiny\rmfamily, % Tiny numbers
  breakindent=0pt,
  breakautoindent=true,
  keepspaces=true,
%  linewidth=0.98\linewidth,
%  numbers=left, % numbers on the left
%  stepnumber=2, % number every second line of code
%   numbersep=5pt, % 5pt seperation between numbering and code listing
  showstringspaces=false,
  literate={°}{\textdegree}1 {ü}{\"{u}}1 {ö}{\"{o}}1 {ä}{\"{a}}1 {Ü}{\"{U}}1 {Ö}{\"{O}}1 {Ä}{\"{A}}1 {ß}{{\ss}}1 {æ}{\ae{}}1 {ø}{\o{}}1 {→}{$\rightarrow$}1,
  upquote=true, % ''
  flexiblecolumns=true,
  inputencoding=utf8,
  language=PHP,
  breaklines=true,
  breakatwhitespace,
  prebreak=\mbox{$\hookleftarrow$},
  frame=none,%brtl,
  morekeywords={% functions ×
  catch,
  pow,
  session_cache_expire, session_decode, session_is_registered, session_regenerate_id, session_save_path, str_replace,
  readFromDb,
  try,
  __autoload,
  __call,
  __clone,
  __construct,
  __destruct,
  __get,
  __isset,
  __set,
  __sleep,
  __toString,
  __wakeup,
  },
  classoffset=2,
  morekeywords={% class + specific words ×
  abstract,
  class,clone,
  extends,implements,interface,
  function,
  new,
  parent,
  },
  keywordstyle=\color{red!50!black},
  classoffset=3,
  morekeywords={% predefined constants ×
    __CLASS__,
    __FILE__,
    __FUNCTION__,
    __LINE__,
    __METHOD__,
    E_ERROR, E_WARNING, E_PARSE, E_NOTICE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR,
    E_COMPILE_WARNING, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_ALL,
    E_STRICT,E_RECOVERABLE_ERROR, E_DEPRECATED, E_USER_DEPRECATED,
    PHP_OS,PHP_VERSION,PREG_SET_ORDER,
    $GLOBALS,$_SERVER,$_GET,$_POST,$_COOKIE,$_FILES,$_ENV,$_REQUEST,$_SESSION,$_SESSION,
  },
  keywordstyle=\bfseries\color{black!80!green!90},
  classoffset=4,
  morekeywords={% predefined constants ×
    final, public, private, protected, static
  },
  keywordstyle=\bfseries\color{blue!50!black!70},
  classoffset=0,
% alsoother={_$},%
% alsoletter={_},%
  escapeinside={(*}{*)},
  morecomment=[s][\color{blue!50!black!70}]{/*}{*/}
}
% exampleblock listing package
  \lstdefinestyle{exampleblock}{frameshape={rnr}{n}{y}{rnr}}

\newcommand{\comment}{\color{gray}}%
\newcommand{\commentBlue}{\bfseries\color{blue!50!black!70}}

\usepackage[%bookmarksopen,
            urlcolor=blue,
            citecolor=blue,
            linkcolor=blue,
            colorlinks=false,
            breaklinks=true,
            draft=false,
            pdftitle={PHP Reference Sheet},
            pdfauthor={Andreas Plank},
            pdfkeywords={PHP, reference sheet, PHP5, free, cheat sheet, short reference},
            pdfsubject={programming help},
            pdfstartview=FitV, % H - horiz.Breite, V - vert.Breite, HB - horiz. Boundingbox (Textkörper)
            pdfpagemode=UseOutlines,  % UseNone - Bookmarks ausblenden; UseThumbs - Thumbs zeigen; UseOutlines - Bookmarks zeigen
            ]{hyperref}              % Verweise als klickbare Links
  \urlstyle{rm} % \url{}
\usepackage{tikz}                  % Zeichnen \tikz draw[->] (1em,0em) -- (2em,1em);
  \usepgflibrary{arrows}
  \usetikzlibrary{backgrounds}

\usepackage{multicol}
\usepackage{titlesec}
% \usepackage{makeidx}                 % Index
%×

% definitions titlepage ×
%   \titlespacing*{ command }{ left }{ beforesep }{ aftersep }[ right ]
  \titlespacing*{\section}{0pt}{*0.1}{*0.0}
  \titlespacing*{\subsection}{0em}{*0.0}{*0.0}
  \titlespacing*{\subsubsection}{0pt}{*0.0}{*0.0}

  % \titleformat*{\section}{\normalfont\normalsize}
  % \titleformat*{\subsection}{\normalfont\normalsize}
  % \titleformat*{\subsubsection}{\normalfont\normalsize}
  % TOC depth countering
  \setcounter{tocdepth}{3}
  \setcounter{secnumdepth}{3}

  \usepackage{colortbl} % für \columncolor
%   \titleformat
%     {name=\section} % commands
%     [block]                     % shape: display, hang, block, frame
%     {\hspace{0.6em}\begin{tabular}[t]{@{}>{\normalsize\sffamily\centering\columncolor{blue!30}}p{0.95\columnwidth}@{}}}      % format
%     {\thesection}                  % label
%     {0.5em}                         % sep <->
%     {\vspace*{-4ex}}            % code before
%     [\label{sec:\thesection}\end{tabular}]    % code after
%   % subsections numberless
%   \titleformat
%     {name=\subsection,numberless} % commands ,numberless
%     [block]                     % shape
%     {\hspace{0.6em}\begin{tabular}[t]{@{}>{\normalsize\sffamily\centering\columncolor{blue!10}}p{0.95\columnwidth}@{}}}      % format: \titlerule*[0.3em]{.}\normalsize\sffamily
%     {\nameref{sec:\thesection}~$>$~}                  % label
%     {0.0em}                         % sep <->
%     {\vspace*{-4ex}}  % code before
%     [\label{subsec:\thesubsection}\end{tabular}]    % code after
%   % subsubsections numberless
%   \titleformat
%     {name=\subsubsection,numberless} % commands
%     [block]                     % shape
%     %{\titlerule*[0.3em]{.}\normalsize\sffamily}      % format
%     {\hspace{0.6em}\begin{tabular}[t]{@{}>{\normalsize\sffamily\centering\columncolor{blue!10}}p{0.95\columnwidth}@{}}}      % format: \titlerule*[0.3em]{.}\normalsize\sffamily
%     {\nameref{sec:\thesection}~$>$~}  % label
%     {0em}                         % sep <->
%     {\nameref{subsec:\thesubsection}\vspace*{-4ex}~$>$~}   % code before
%     [\end{tabular}]    % code after
  \newlength{\thesectionlenght}
  \titleformat
    {name=\section} % commands
    [block]                     % shape: display, hang, block, frame
    {\hspace{0.6em}\begin{tabular}[t]{@{}>{\normalsize\sffamily\centering\columncolor{blue!30}}p{0.95\columnwidth}@{}}}      % format
    {}                  % label
    {0em}                         % sep <->
    {\vspace*{-4ex}}            % code before
    [\label{sec:\thesection}\end{tabular}\settowidth{\thesectionlenght}{(\thesection}\hspace*{-\thesectionlenght}(\thesection)]    % code after
  % subsections numberless
  \titleformat
    {name=\subsection} % commands ,numberless
    [block]                     % shape
    {\hspace{0.6em}\begin{tabular}[t]{@{}>{\normalsize\sffamily\centering\columncolor{blue!10}}p{0.95\columnwidth}@{}}}      % format: \titlerule*[0.3em]{.}\normalsize\sffamily
    {\nameref{sec:\thesection}~$>$~}                  % label
    {0.0em}                         % sep <->
    {\vspace*{-4ex}}  % code before
    [\label{subsec:\thesubsection}\end{tabular}\settowidth{\thesectionlenght}{(\thesubsection}\hspace*{-\thesectionlenght}(\thesubsection)]    % code after
  % subsubsections numberless
  \titleformat
    {name=\subsubsection} % commands,numberless
    [block]                     % shape
    %{\titlerule*[0.3em]{.}\normalsize\sffamily}      % format
    {\hspace{0.6em}\begin{tabular}[t]{@{}>{\normalsize\sffamily\columncolor{blue!10}}p{0.95\columnwidth}@{}}}      % format: \titlerule*[0.3em]{.}\normalsize\sffamily
    {\nameref{sec:\thesection}~$>$~}  % label
    {0em}                         % sep <->
    {\nameref{subsec:\thesubsection}\vspace*{-4ex}~$>$~}   % code before
    [\end{tabular}\settowidth{\thesectionlenght}{(\thesubsubsection}\hspace*{-\thesectionlenght}(\thesubsubsection)]    % code after

  % \titleformat{command}[shape]{format}{label}{sep}{before}[after]
  % sections numbered
  % \titleformat
  %   {name=\section} % commands
  %   [hang]                     % shape
  %   {\titlerule[0.8pt]\vspace*{0.5ex}\normalsize\sffamily}      % format
  %   {\thesection}                  % label
  %   {0.5em}                         % sep <->
  %   {\centering}            % code before
  %   [\label{sec:\thesection}]    % code after
  % % subsections numberless
  % \titleformat
  %   {name=\subsection,numberless} % commands
  %   [hang]                     % shape
  %   {\titlerule*[0.3em]{.}\normalsize\sffamily}      % format
  %   {\nameref{sec:\thesection}}                  % label
  %   {0.0em}                         % sep <->
  %   {~$>$~}            % code before
  %   []    % code after
  % % subsubsections numberless
  % \titleformat
  %   {name=\subsubsection,numberless} % commands
  %   [hang]                     % shape
  %   {\titlerule*[0.3em]{.}\normalsize\sffamily}      % format
  %   {\nameref{sec:\thesection}}  % label
  %   {0em}                         % sep <->
  %   {~$\ggg$~}            % code before
  %   []    % code after
  %%%%%%%%
  % \titleformat{command}[shape]{format}{label}{sep}{before}[after]
  % \titleformat
  %   {name=\chapter,numberless}
  %   [display]
  %   {\normalfont\Large\bfseries}
  %   {\hrulefill}
  %   {0pt}
  %   {\centering\large}
  %   [\vspace*{-1ex}\hrulefill]

% × tikz icons
  % sort funktion
  \newcommand{\sort}[1][->]{\begin{tikzpicture}[scale=0.5,overlay]
  \ifthenelse{\equal{#1}{->}}
  {\foreach \key/\val/\pos in {0/A/3.5,1/B/1.0,2/C/-1.5}}% if ->
  {\ifthenelse{\equal{#1}{ok<-}}% old keys
    {\foreach \key/\val/\pos in {2/C/3.5,1/B/1.0,0/A/-1.5}}
    {\foreach \key/\val/\pos in {0/C/3.5,1/B/1.0,2/A/-1.5}}}% if otherwise
    \path node[scale=0.5] (zero\val)  at (0.0em,\pos ex) {\key}
          node[scale=0.5] (asign) at (1.3em,\pos ex) {=>}
          node[scale=0.5] (three\val) at (2.8em,\pos ex) {\val};
    \draw[->,line width=1pt, scale=0.5] (threeA.east) -- (threeC.east);
  \end{tikzpicture}}
  % ksort keysorts
  \newcommand{\ksort}[1][->]{\begin{tikzpicture}[scale=0.5,overlay]
  \ifthenelse{\equal{#1}{->}}
  {\foreach \key/\val/\pos in {0/A/3.5,1/B/1.0,2/C/-1.5}}
  {\foreach \key/\val/\pos in {2/C/3.5,1/B/1.0,0/A/-1.5}}
    \path node[scale=0.5] (zero\val)  at (0.0em,\pos ex) {\key}
          node[scale=0.5] (asign) at (1.3em,\pos ex) {=>}
          node[scale=0.5] (three\val) at (2.8em,\pos ex) {\val};
    \draw[->,line width=1pt, scale=0.5] (zeroA.west) -- (zeroC.west);
  \end{tikzpicture}}
  %  data types
    % boolean
    \newcommand{\bool}{%\begin{tikzpicture}[inner sep=0pt, scale=0.7]
      %\node[scale=0.7]  (true) at (0em,1ex) {T};
      %\node[scale=0.7] (false) at (0.7em,0ex) {F};
      %\draw[yshift=0.0ex] (-0.2em,0ex) -- (0.8em,1.5ex);
    %\end{tikzpicture}
      \begin{tikzpicture}
      \node[draw, scale=0.6] {T/F};
    \end{tikzpicture}}
    % \integer
    \newcommand{\integer}{\begin{tikzpicture}
      \node[draw, scale=0.6] {0-9};
    \end{tikzpicture}}
    % \float
    \newcommand{\float}{\begin{tikzpicture}
      \node[draw, yscale=0.6,xscale=0.4] {1.209};
    \end{tikzpicture}}
    % \strg
    \newcommand{\strg}{\begin{tikzpicture}
      \node[draw, scale=0.6] {A-Z};
    \end{tikzpicture}}
    % array
    \newcommand{\arr}{\begin{tikzpicture}[scale=0.25,baseline]
    \foreach \key/\val/\pos in {0/A/4.5,1/B/2.0,2/C/-0.5}
      \path node[scale=0.3] (zero\val)  at (0.0em,\pos ex) {\key}
            node[scale=0.3] (asign) at (1.3em,\pos ex) {=>}
            node[scale=0.3] (three\val) at (2.8em,\pos ex) {\val};
      \draw (-1em,-2ex) rectangle (4em,6ex);
    \end{tikzpicture}}
    % object
    \newcommand{\obj}{\begin{tikzpicture}
      %\shade[ball color=gray] (0em,1ex) circle (0.8ex) node[color=white,font=\bfseries, inner sep=0pt,scale=0.35] {Obj};
      \draw[fill=gray, color=gray] (0em,1ex) circle (0.8ex) node[color=white,font=\bfseries, inner sep=0pt] {O};
    \end{tikzpicture}}
    % resource
    \newcommand{\resource}{\begin{tikzpicture}
    \shade[ball color=gray!50]  (0em,1ex)  circle (0.8ex);
    \draw[line width=2pt,shorten >=2pt]  (1.0ex,2ex) -- (0.0ex,0.5ex);
    \draw[-triangle 60,white,very thin]       (1.0ex,2ex) -- (0.0ex,0.5ex);
    \draw[-open triangle 60,very thin]        (1.0ex,2ex) -- (0.0ex,0.5ex);
    \end{tikzpicture}}
    % \NULL
    \newcommand{\NULL}{\begin{tikzpicture}
      \node[draw, yscale=0.6,xscale=0.45] {NULL};
    \end{tikzpicture}}
    % \void
    \newcommand{\void}{\begin{tikzpicture}
      \node[draw, yscale=0.6,xscale=0.45] {void};
    \end{tikzpicture}}
    % \mixed
    \newcommand{\mixed}{\begin{tikzpicture}
      \node[draw, yscale=0.6,xscale=0.4] {mixed};
    \end{tikzpicture}}
  % pencil with paper block
  \newcommand{\example}{%
    \begin{tikzpicture}[overlay]
      \draw (0em,0ex) rectangle (1em,2ex);
      \foreach \y in {0.4,0.6,...,1.8}  \draw[very thin] (0.2em,\y ex) -- (0.8em,\y ex);
      \foreach \x in {0.2,0.4,...,0.8}  \draw[thin] (\x em,1.8ex) arc (270:0:0.2ex);
      \draw[line width=3pt,shorten >=2pt]                             (1em,2ex) -- (0.5em,0.5ex);
      \draw[line width=3pt,-triangle 90 cap,shorten >=-1.0pt]         (1em,2ex) -- (0.5em,0.5ex);
      \draw[line width=2pt,shorten >=1.5pt,shorten <=0.5pt,red!50!yellow] (1em,2ex) -- (0.5em,0.5ex);
    \end{tikzpicture}\hspace*{1.0em}}
  % info
    \newcommand{\info}[1]{%
    \begin{minipage}[c]{1em}
      \begin{tikzpicture}%[baseline=(current bounding box.north)]%
          \draw (0em,0ex) rectangle (1em,2ex);%
          \foreach \x in {0.2,0.4,...,0.8}  \draw[thin] (\x em,1.8ex) arc (270:0:0.2ex);%
          \draw[anchor=mid] (0.5em,0.7ex) node{i};%
      \end{tikzpicture}\end{minipage}~\begin{minipage}{\columnwidth-2em}
    \tikz \node [inner sep=0pt,text width=\textwidth,font=\rmfamily\scriptsize] {#1};
    \end{minipage}}%

    \newcommand{\warn}{%
      \begin{tikzpicture}%[baseline=(current bounding box.north)]%
          \draw (0em,0ex) rectangle (1em,2ex);%
          \foreach \x in {0.2,0.4,...,0.8}  \draw[thin] (\x em,1.8ex) arc (270:0:0.2ex);%
          \draw[anchor=mid, color=red] (0.5em,0.7ex) node{!};%
      \end{tikzpicture}}%

    \newcommand{\phplogo}[1][1]{
    \begin{tikzpicture}[anchor=center, scale=#1]
      \clip[scale=1.1] (0,0) ellipse (2em and 1em);
       \shadedraw [shading=ball,ball color=white,scale=1.1,draw=none] (0,0) ellipse (2.5em and 1.2em);
       \draw [fill=blue!30, draw=none] (0,0) ellipse (2em and 1em);
       \node[font=\itshape\bfseries,scale=1.7,white] (0,0) {php};
       \node[font=\itshape,xscale=1.8,yscale=1.7] (0,0) {php};
    \end{tikzpicture}}

% title ×
  \title{PHP Referenz}
  \author{Andreas Plank}

\parindent0em\parskip0ex

% \makeindex
\begin{document}


\begin{multicols}{3}
\begin{center}
  \phplogo[1, overlay, xshift=-5em, yshift=-0.7ex] {\bfseries\Large PHP Reference Sheet}\\
  \href{mailto:andreasDotplankAtwebDotde?subject=PHP-Reference}{Andreas Plank} (version \today)\\
  License: \href{http://creativecommons.org/licenses/by-nc-sa/3.0/}{Creative Commons Noncommercial Share Alike 3.0}
\end{center}

\section{Basics}
\subsection{Comments}
\begin{lstlisting}
// Comment text
/* Multi-line comment text */
# Comment text
\end{lstlisting}

\subsection{Data Types}
\begin{lstlisting}
(*\bool*) bool boolean /* false, true */
(*\integer*) int integer /* -1, 2, 0 */
(*\float*) float   /* 1.3445363 */
(*\strg*) string /* 'text' */
(*\arr*) array  /* $arr=array("key"=>"value", "something");*/
(*\obj*) object  /* see class(*\comment\vpageref{sec:classes}*) */
(*\resource*) resource /* external reference: pdf, aspell */
(*\NULL*) NULL  /* unset(), set NULL, not yet set */
\end{lstlisting}

\subsection{Recommended Naming Rules/Documentation}
\begin{lstlisting}
# Hungarian notation e.g.: $boolPost, $strContent ...
$intXxx or $iXxx # integer
$floatXxx or $fXxx # float
$doubleXxx or $dXxx # double==float
$strXxx or $sXxxx # string
$arrXxx or $aXxx # array
$boolXxx or $bXxx # boolean 'true' 'false'
$objXxx or $oXxx # object
/* classes, methods, objects */
class classText # use a noun with classes/objects
$objText = new classText();
# functions with verbs: get.. add... has... etc.
$objText->readFromDb(); # not $objText->readTextFromDb();
/** (*\commentBlue see phpDocumentor \url{http://phpdoc.org/}*)
 * showing a head line (short description)
 * bla bla bla (long description ...)
 * @author Max Muster <max@foo.bar>
 * @param string $strHead text for headings/sections
 * @param int $intSize=12 font size in pt
 * @return string in different sizes
 */
function showHeadline($strHead, $intSize=12){
  return "<h1 style=\"font-size:$intSize pt;\">$strHead</h1>";
}
\end{lstlisting}

\subsection{Super Globals/Magic Constants}
\begin{lstlisting}
$GLOBALS  #Access all global variables in script
$_SERVER  #Access web server variables
  ['PHP_SELF'] # /folder/testphp.php, file without root
  ['SCRIPT_NAME'] # /folder/testphp.php, file without root
  ['DOCUMENT_ROOT'] # /absolute/root/web/dir
  ['SCRIPT_FILENAME'] # /absolute/script/path/index.php
  ['REMOTE_ADDR'] # remote IP from user 91.64.225.29
  ['REMOTE_HOST'] # remote hostname
  ['REQUEST_URI'] # requested URL from current page
$_GET     #Values passed to script through URL
  ['nameOfFormElement'] = <value>
$_POST    #Values passed to script through HTTP Post
  ['nameOfFormElement'] = <value>
$_COOKIE  #Values passed by user cookie
$_FILES   #Values passed by HTTP Post File Uploads
  ['inputTagName']['name'] /* original file name of the file on the client machine. */
  ['inputTagName']['type'] /* The mime type NOT PHP checked! */
  ['inputTagName']['size'] /* The size: bytes */
  ['inputTagName']['tmp_name'] /* temporary filename on the server. */
  ['inputTagName']['error'] /* The error code associated with this file upload.*/
$_ENV     #Values passed to script via the environment
$_REQUEST #Values passed by URL, HTTP Post, Cookies
$_SESSION #Values passed through user's session
__LINE__  # current line number of the file
__FILE__  # full path and filename of the file.
(*\info{If used inside an include, the name of the included file is returned. Since PHP 4.0.2, \texttt{\_\_FILE\_\_} always contains an absolute path whereas in older versions it contained relative path under some circumstances.}*)
__FUNCTION__  # The function name
__CLASS__   # class name
__METHOD__  # function name or class::method
\end{lstlisting}

\subsection{External (Script) Files}
\begin{lstlisting}
# Warnings + Fatal Errors given:
include '[url/]file.php';
include_once '[url/]file.php';
(*\info{Variables as \texttt{\$\_SERVER} used in the file included return the current path not the path from included file itself.}*)
(*\example*) include 'http://www.xxx.com/file.php?foo=1&bar=2';
# Warnings = Fatal Error!
require '[url/]file.php';
require_once '[url/]file.php';
(*\integer*) readfile('[url/]file.php'); /* reads a file
and writes it immediately to the output buffer */
(*\strg*) file_get_contents('[url/]file.php');
(*\example*) # get contents of a file into a string:
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
\end{lstlisting}


\subsection{Outputs}
\begin{lstlisting}[frame=none, belowskip=0ex]
(*\integer*) print( string $arg ); # Output a string
(*\void*) echo( string $arg1 [, string $... ] );
(*\mixed*) print_r( mixed $expression [, bool $return ]);
\end{lstlisting}

\subsection{Declare Variables Constants}
\begin{lstlisting}[style=exampleblock]
(*\example*) /* type casiting + declaration printed with:
 echo("Hello ".print_r($test, true)."!"); */
$test  = (string) "world";   # Hello world!
$test  = (string) array("Hello", "world"); # Hello Array!
$test  = (bool)    "world";  # Hello 1!
$test  = (boolean) "world";  # Hello 1!
$test  = (int)     "world";  # Hello 0!
$test  = (integer) "world";  # Hello 0!
$test  = (float)   "world";  # Hello 0!
$test  = (double)  "world";  # Hello 0!
$test  = (real)    "world";  # Hello 0!
$test  = (array)   "world";
  # Hello Array ( [0] => world ) !
$test  = (object)  "world";
  # Hello stdClass Object ( [scalar] => world ) !
/* declare long strings */
$file=(*\ttfamily\textcolor{blue}{<<<EOD}*)
hello world here
is mucht text ...
(*\ttfamily\textcolor{blue}{EOD}*);
# end here
/* declare constants: not changable */
  define("FOO", "something");
  define("FOO2", "something else");# 2FOO is invalid
  define("FOO_BAR", "something more");
\end{lstlisting}

\subsection{Arithmetic Operators/Calculations}
\begin{lstlisting}
+, -, *, /, % /*Modulus*/
(*\example*) 5 % 3; # gives 2 (remainder 2 of 5 divided by 3)
pow(2,8); # (*\comment 2$^8$*)
sqrt(10); # (*\comment $\sqrt[2]{10}$*)
exp(<float>) # (*\comment $e^\mathtt{<float>}$*)
log(<nfloat>[, <bfloat>]) # (*\comment $\log_bn$*)
pi() # (*\comment 3.1415926\,$\ldots$\, $\pi$*)
\end{lstlisting}

\subsection{Relational/Logical Operators}
\begin{lstlisting}
$a == $b  # equal
$a === $b # identical: equal + same type
$a != $b  # not equal
$a <> $b  # not equal
$a !== $b # not identical: not equal + not same type
$a < $b   # less than
$a > $b   # greater than
$a <= $b  # less than or equal to
$a >= $b  # greater than or equal to
$a and $b # And: if both $a and $b are TRUE.
$a && $b  # And: if both $a and $b are TRUE.
$a or $b  # Or: if either $a or $b is TRUE.
$a || $b  # Or: if either $a or $b is TRUE.
$a xor $b # Xor: if either $a or $b is TRUE, but not both
!$a       # Not: if $a is not TRUE.
\end{lstlisting}

\subsection{Assignment Operators (from right)}
\begin{lstlisting}
=, +=, -=, *=, /=, .=, %=, &=, |=, ^=, <<=, >>=
= /*assign*/ += /*addition*/ -= /*subtraction*/
(*\example*) $a = 3; $a += 5; # $a = 8 same as: $a = $a + 5;
*= /*multiplication*/ /= /*division*/
.= /*concatenation*/
(*\example*) $b = "Hello "; $b .= "There!"; # "Hello There!"
%= /*modulus*/ &= /* reference*/
(*\info{References in PHP are a means to access the same variable content by different names. Note that in PHP, variable name and variable content are different, so the same content can have different names. The most close analogy is with Unix filenames and files - variable names are directory entries, while variable contents is the file itself. }*)
|= /*or*/ ^= /*exclusive or*/
<<= /*left shift bitwise*/ >>= /*right shift bitwise*/
(*\info{Bitwise operators allow you to turn specific bits within an integer on or off. If both the left- and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.}*)
\end{lstlisting}



\section[Manipulation]{Manipulation Variable/Array}
\begin{lstlisting}
$var = <value>;
$var = (string) <value>;
$anothervar =& $var; # assigned by reference
$arr = array();
$arr = array(# keys not explicit defined
  <val1>, # key starts at 0: $arr[0]
  <val2>, # $arr[1]
  <val3>  # $arr[2]
);# end array()
$arr = array(# keys defined
  <key1> => <value>,
  <key2> => <value>
);# end array()
$multiarr = array(# multi-dimensional
  <key> => array(<value1>,<value2>)
);# end multi array()
\end{lstlisting}

\subsection[Array]{Array Functions}

\begin{lstlisting}[frame=none, belowskip=0ex]
(*\bool*) sort(<arr>); #  values + new keys (*\sort*)
(*\bool*) rsort(<arr>); # values reverse + new keys (*\sort[<-]*)
(*\bool*) asort(<arr>); #  values + old keys (*\sort*)
(*\bool*) arsort(<arr>);# values reverse + old keys (*\sort[ok<-]*)
(*\bool*) ksort(<arr>); # sort keys  (*\ksort*)
(*\bool*) krsort(<arr>); # sort keys reverse  (*\ksort[<-]*)
(*\bool*) natsort(<arr>); # natural sorting
(*\integer*) count(<arr>); # count elements
(*\integer*) count(<arr>,COUNT_RECURSIVE); # count multidimensional
(*\arr*) array_push(<arr>,<val>); # push item onto the end
(*\arr*) array_pop(<arr>); # pop item off from end
(*\arr*) array_shift(<arr>); # shift item off from begin
(*\arr*) array_slice(<arr>, off [, len]); # extract a slice
(*\arr*) array_splice(<arr>, off [, len [, repl]]);
# remove a portion of an array (and do replace)
(*\void*) list(mixed varname, mixed ... )
\end{lstlisting}
\begin{lstlisting}[frameshape={rnr}{n}{y}{rnr}, aboveskip=0ex]
(*\example*) $info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color with $power.\n";
\end{lstlisting}

 \begin{lstlisting}
(*\arr*) array_values(<arr>) # values + new index
(*\arr*) array_keys(<arr>) # return keys
(*\arr*) array_unique(<arr>) # without duplicates
(*\arr*) array_merge(<arr1>,<arr2>) # number integer keys anew
(*\bool*) in_array('string/float', <arr> [, bool strict])
  # check for values
(*\mixed*) array_search('string/float', <arr> [, bool strict])
  # returns the corresponding key if successful or (*\bool*)
\end{lstlisting}


% \enlargethispage*{0.5cm}

\subsection[Strings]{String Manipulation}\label{sec:strings}
% For safe unicode handling use the multibyte string functions \lstinline~mb_...~.
\hr{} Use multibyte string functions \lstinline~mb_...~ for unicode handling.
\begin{lstlisting}
(*\strg*) substr(<str>,<start>,[<len>]); # subsring
(*\integer*) strlen(<str>); # length of string
trim(<str> [, charlist] );
ltrim(<str> [, charlist] ); # trim left
rtrim(<str> [, charlist] ); # trim right
(*\info{strip whitespace/other characters from the beginning and/or end of a string}*)
\end{lstlisting}
\begin{lstlisting}[style=exampleblock]
(*\example*) $text = "\t\tThese are a few words :) ...  ";
echo trim($text); # "These are a few words :) ..."
echo trim($text, " \t.");#"These are a few words :)"
$trimmed = ltrim($text, " \t.");
# left trimmed: "These are a few words :) ...  "
$clean = ltrim($binary, "\x00..\x1F");
(*\info{trim ASCII control characters at the beginning of \$binary (from 0 to 31 inclusive)}*)
\end{lstlisting}
\begin{lstlisting}
strtolower(<str>); # STRING -> string
strtoupper(<str>); # string -> STRING
str_replace(<search>, <repl.>, <str>,[<count>]);
preg_replace(<search>, <repl.>, <str>,[<limit>[,&count]);
(*\info{every parameter in \texttt{str\_replace()} can be an array}*)
\end{lstlisting}
\begin{lstlisting}[style=exampleblock]
(*\example*) # Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
\end{lstlisting}
\begin{lstlisting}
(*\integer*) strpos(<str>, <search>); # first string occurrence
(*\example*) $newstring = 'abcdef abcdef';
    $pos = strpos($newstring, 'a', 1);# $pos = 7, not 0
strcmp(<string1>,<string2>); # binary safe string compare
strncmp(<string1>,<string2>,<len>);
# binary safe string comparison of the first n characters
strcasecmp(<string1>,<string2>);
# binary safe case-insensitive comparison
(*\info{all \texttt{\,$\ldots$\,cmp()} return < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.}*)
strip_tags(<str>,[<allowable tags>]);# remove PHP/HTML
(*\example*) $text = '<p>Test paragraph.</p><!-- Comment --> Other text';
    echo strip_tags($text);# 'Test paragraph. Other text'
eval("return $value;"); # evaluates the string
(*\arr*) explode(<delim>,<str>,[<limit>]);
    # Break string into array
(*\strg*) implode(<delim>,<array>);
    # Join array into string separated by delim
(*\strg*) rawurlencode("strings /?'ü'ß"); # 'historical'
  # strings%20%2F%3F%27%C3%BC%27%C3%9F
(*\strg*) urlencode("strings /?'ü'ß"); # should be used
  # strings+%2F%3F%27%C3%BC%27%C3%9F
(*\strg*) htmlentities("strings /?'ü'ß",ENT_QUOTES, 'UTF-8');
  # strings /?&#039;&uuml;&#039;&szlig;
(*\strg*) utf8_encode("iso-8859-1"); # utf8 <- iso-8859-1
(*\strg*) utf8_decode("utf8"); # iso-8859-1 <- utf8
\end{lstlisting}

\subsubsection{Formatted Strings}
\begin{lstlisting}
(*\strg*) s|printf( (*\strg*) <format> [, mixed args [, mixed ...]]);
(*\example*) echo sprintf("%04d-%02d-%02d", $year, $month, $day);
$n =  439; $u = -439; $c = 65; // ASCII 65 is 'A'
# notice double %%, this prints a literal '%' character
printf("%%b = '%b'\n", $n);# %b = '110110111' binary(*\comment 011$_\mathtt{2}$*)
printf("%%c = '%c'\n", $c);# %c = 'A', same as chr()
printf("%%d = '%d'\n", $n);# %d = '439' 'decimal'(*\comment 123$_\mathtt{10}$*)
printf("%%e = '%e'\n", $n);# %e = '4.39000e+2' scientific
printf("%%u = '%u'\n", $n);# %u = '439' unsigned(*\comment 123$_\mathtt{10}$*)
printf("%%u = '%u'\n", $u);# %u = '4294966857' from neg.
printf("%%f = '%f'\n", $n);# %f = '439.000000' floating
printf("%%o = '%o'\n", $n);# %o = '667' octal(*\comment 123$_\mathtt{8}$*)
printf("%%s = '%s'\n", $n);# %s = '439' as 'sting'
printf("%%x = '%x'\n", $n);# %x = '1b7' hexadecimal lower
printf("%%X = '%X'\n", $n);# %X = '1B7' hexadecimal UPPER
printf("%%+d= '%+d'\n",$n);# %+d = '+439' +/-(*\comment 123$_\mathtt{10}$*)
printf("%%+d= '%+d'\n",$u);# %+d = '-439' +/-(*\comment 123$_\mathtt{10}$*)
/* padding or cutoff */
$s = 'monkey'; $t = 'many monkeys';
printf("[%s]\n",      $s);# [monkey]     standard output
printf("[%10s]\n",    $s);# [    monkey] right adjust
printf("[%-10s]\n",   $s);# [monkey    ] left adjust
printf("[%010s]\n",   $s);# [0000monkey] zero padding
printf("[%'#10s]\n",  $s);# [####monkey] #-padding
printf("[%10.10s]\n", $t);# [many monke] cutoff
/* referring to positions */
$format = 'That\'s a nice %2$s full of %1$d monkeys.';
printf($format, 3, 'place');
# That\'s a nice place full of 3 monkeys.
\end{lstlisting}

\subsubsection{Formatted Date}
% date()
% date_sunrise()
% date_sunset()
\begin{lstlisting}
date("r"); # Sun, 14 Dec 2008 14:01:24 +0100
date("F j, Y, g:i a<b\\r>");# December 13, 2008, 3:17 pm
date("m.d.y<b\\r>");  # 12.13.08
date("j, n, Y<b\\r>");# 13, 12, 2008
date("Ymd<b\\r>");    # 20081213
date('h-i-s, j-m-y, it is w Day z <b\r>');
  #03-17-04, 13-12-08, 1731 1704 6 Satpm08 347
/* escaping */
date('\i\t \i\s \t\h\e jS \d\a\y.<b\r>');
  # it is the 13th day.
date("D M j G:i:s T Y<b\\r>");
  # Sat Dec 13 15:17:04 CET 2008
date('H:m:s \m \i\s\ \m\o\n\t\h<b\r>');
  # 15:12:04 m is month
date("H:i:s<b\\r>"); # 15:17:04
\end{lstlisting}


\section{Searching}
\subsection{Regular Expressions}
\begin{lstlisting}
^ # at beginning of a string: "/^cat/" any string 'cat..'
$ # at the end of strings "/cat$/" any string '...cat'
. # any single character "/cat./" -> catT, cat2 NOT catty
() /*a(bee)?t -> at, abeet NOT abet or ref to found \\1*/
[] # character class: gr[ae]y matches gray or grey
[^] # without-expression: 1[^02] -> 13 but not 10 or 12
[-] # ranges, [1-9] matches 1,2..,9 EXCEPT 0; [a-züßæ]
### Quantifiers
? # 0, 1 times: colou?r -> color, colour NOT colouur
+ # 1, multiple times: be+ -> be, bee NOT b
* # 0, multiple times: be* -> b, be, beeeeeeeeee
{n} # pattern n-times: /'[0-9]{3}'/ -> 264 NOT 12 or 8372
{n,} # n-times or more: '/[0-9]{3,}/' 347, 92038, 9074
{n,m} # n to m-times: '/[0-9]{3,5}/'  any 3, 4, 5 digits
| # alternatives: July (first|1st|1) -> 'July 1st' NOT 'July 2'
### Character Definition  Example
[:alnum:] /* alpha-numeric character: [[:alnum:]]{3} -> letters/numbers [a-z0-9] like '7Ds' */
[:alpha:] /* alphabetic character: [[:alpha:]]{5} -> 5 alphabetic characters, any case, like aBcDe */
[:blank:] /* space and tab [[:blank:]]{3,5} matches any 3, 4, or 5 spaces and tabs */
[:digit:] /* digits  [[:digit:]]{3,5} matches any 3, 4, or 5 digits, like 3, 05, 489*/
[:lower:] /* lowercase alphabetics [[:lower:]] */
[:upper:] /* UPPERCASE alphabetics [[:upper:]] */
[:punct:] /* punctuation characters [[:punct:]] -> ! or . or , NOT 'a' or '3' */
[:space:] /* all whitespace characters: [[:space:]] space, tab, newline, or carriage return */
### Perl-Style Metacharacters
// # Default delimiters: '/colou?r/' finds color or colour
i /* (PCRE_CASELESS) case insensitive: /colou?r/i matches COLOR or Colour */
m /* (PCRE_MULTILINE)  multi line search: '/^.+$/m' -> a whole line */
s /* (PCRE_DOTALL) '.' matches all characters, including newlines */
e # evaluate PHP
U # ungreedy: '/<a.+>/U' finds single link tags
u # pattern strings are treated as UTF-8
x # space is ignored
### escaping strings
\b /* word boundary: spot between word (\w) and non-word (\W) characters  /\bfred\b/i matches Fred but not Alfred or Frederick */
\B /* non-word boundary /fred\B/i -> Frederick but not Fred */
\d # a single digit: /a\db/i matches a2b NOT acb
\D # a single non-digit: /a\Db/i matches aCb but not a2b
\n # The newline character. (ASCII 10) /\n/ -> newline
\r # the carriage return character (ASCII 13)
\s # a single whitespace: /a\sb/ matches 'a b' NOT 'ab'
\S # non-whitespace character /a\Sb/ matches 'a2b'  'a b'
\t # the tab character. (ASCII 9)
\w /* single word: alphanumeric + underscore /\w/ -> '1' or '_' NOT '?' */
\W /* single non-word: /a\Wb/i matches a!b NOT a2b
\end{lstlisting}
\begin{lstlisting}[style=exampleblock]
(*\example*) ### e = evaluates code
'/(.+)/e' -> 'strip_tags("\\1", "<img><a>")'
'/(.+)/e' -> '\'\\1\'==\'text\'?\',\':\'\''
#'text' == 'text'?',':''; → if identical ',' else ''
### greedy/ungreedy
"/\<style.*[^\/]>.+<\/style>/U" # remove CSS
\end{lstlisting}

\subsection{Common Functions}
\begin{lstlisting}
(*\strg*) str_replace(<search>,<replace>,<str>,[<count>]);
(*\info{Every parameter in \texttt{str\_replace()} can be an array, If no regular expressions are needed take this function}*)
### replace string/array by regular Expressions
(*\strg*) preg_replace(<search>, <repl.>, <str>, [<limit>[,&count]);
  # <search>,<replace>,<str> can be an array()
(*\integer*) preg_match_all(<search>, <str>, (*\arr*) &matches [,(*\integer*) flags [,(*\integer*)  offset]])
### extract array by regular Expressions
(*\arr*) preg_grep(<search>, <array>);
(*\example*) $arrayOut = preg_grep("/^(\d+)?\.\d+$/", $array);
  # only float numbers
\end{lstlisting}

\section{Cookies}
\begin{lstlisting}
(*\bool*) setcookie(<cookiename>, [<value>], [<expire_time_in_secs_since_epoch>], [<path>], [<domain>], [(*\bool*) <secure>], [(*\bool*) <httponly>]);
(*\info{Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has.}*)
(*\example*) $value = 'something from somewhere';
  setcookie("TestCookie",$value,time()+3600);
  # expire in 1h
$_COOKIE['cookiename']; # Returns value of cookie
\end{lstlisting}

\section{Sessions}
\begin{lstlisting}
(*\bool*) session_start(); # Create session
(*\example*) $_SESSION['key_name'] = value; #set variable
    $variablename = $_SESSION['key_name']; # return value
(*\bool*) session_destroy(); # Destroy session
(*\integer*) session_cache_expire(<0-9>);
# return current cache expire given in minutes
(*\strg*) session_cache_limiter(<str>);
(*\info{get and/or set the current cache limiter: 'nocache' disallows any client/proxy caching, 'public' permits caching by proxies and the client, 'private' disallows caching by proxies and permits the client to cache the contents.}*)
(*\bool*) session_decode(<string data>);# decodes data
(*\strg*) session_encode();#encodes the current session data
(*\arr*) session_get_cookie_params()#get session cookie params
(*\strg*) session_id([<str>]); # get and/or set the current session id
(*\bool*) session_is_registered(<str>); # find out whether a global variable is registered in a session
(*\strg*) session_name([str])
# get and/or set the current session name
(*\bool*) session_regenerate_id()
# update the current session id with a newly generated one
(*\bool*) session_register(<str>[, <str>]) # register one or more global variables with the current session
(*\strg*) session_save_path([<str>])
# get and/or set the current session save path
(*\void*) session_set_cookie_params((*\integer*) lifetime [, <path> [, <domain> [, (*\bool*) <secure> [, (*\bool*) httponly]]]])
# set the session cookie parameters
(*\bool*) session_set_save_handler("open", "close", "read", "write", "destroy", "gc") # sets user-level session storage by same-named functions
(*\bool*) session_unregister(<name>)
# unregister a global variable from the current session
(*\void*) session_unset() # free all session variables
(*\void*) session_write_close()
# write session data and end session
\end{lstlisting}

\section{Error Handling}
\begin{lstlisting}
try {# PHP 5
  <statements that may cause error>;
} catch(<Exception Class> $exception_name){
  <statements to execute when error is caught>;
}# end catch
(*\bool*) trigger_error( 'error_msg' [, int type ] )
(*\example*) trigger_error("Error in ".__METHOD__." ...", E_USER_ERROR);
# 'Error in function name ...' -> FATAL ERROR
\end{lstlisting}

\section{Control Structure}
\subsection{If Else}
\begin{lstlisting}
if (<condition 1>)
  { <statement 1>; }
elseif (<condition 2>)
  { <statement 2>; }
else
  { <statement 3>; }
<condition>? true : false; # "?:" ternary operator
(*\example*) echo ((true ? 'true' : 'false') ? 't' : 'f'); # 't'
\end{lstlisting}

\subsection{For Loop/Increments}
\begin{lstlisting}[frame=none, belowskip=0ex]
for (<initialize>;<condition>;<update>)
{<statements>;}
\end{lstlisting}
\begin{lstlisting}[frameshape={rnr}{n}{y}{rnr}, aboveskip=0.5ex, belowskip=0ex]
(*\example*) # numbers from 1 ... 10
for($i = 1; $i <= 10; $i++) echo $i;
for($i = 1; ; $i++) {
  if ($i > 10) break;
  echo $i;
}# end for()
for($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
for($i=0; $i<count($array); $i++)
  echo "\n  <option value='".$i."' ".# compare with $i
  ($someInteger==$i?"selected":"").">".$array[$i];
\end{lstlisting}
\begin{lstlisting}[aboveskip=0ex]
++$a  # Pre-increment by one: $a = $a + 1
--$a  # Pre-decrement by one: $a = $a + 1
$a++  # Post-increment: Returns $a, THEN $a = $a + 1
$a--  # Post-decrement: Returns $a, THEN $a = $a - 1
\end{lstlisting}

\subsection{For Each Loop}
\begin{lstlisting}
foreach (<array> as [<value> | <key> => <value>])
{<statements>;
  [break;]
  [continue;]
}# end foreach()
(*\example*) $arr = array(1, 2, 3, 4); # PHP 5
foreach ($arr as &$value)
  $value = $value * 2; # $arr is now array(2, 4, 6, 8)
\end{lstlisting}

\subsection{While/Do-While Loop} % endlosschleife!
\begin{lstlisting}
while (<condition>) # do if 'condition' is TRUE
  {<statements>;}
(*\example*) $i = 1;
while($i <= 10) {
 echo $i++.(($i<=10)?",":"");#if $i(*$\leqq$*)10 then "," else ""
} # 1,2,3,4,5,6,7,8,9,10
do{<statements>;}# do if 'condition' is TRUE, check at end
while (<condition>);
\end{lstlisting}

\subsection{Switch}
\begin{lstlisting}
switch ($i) { # value or expression
case 0: /* literal or type*/
  echo "i is equal to 0"; break;
case 1:
  echo "i is equal to 1"; break;
default:
  echo "i is neither 0 or 1"; /* a default value */
}# end switch
\end{lstlisting}

\section{Programming}
\subsection{Function Structure}
\begin{lstlisting}
function <functionName>([<parameters>='default'])
{<statements>;
  [return <value>;] // returns + stop function here!!!
  <further statements>
}# end functionName()
@doSomething(<parameter>); # @-supresses error messages
\end{lstlisting}

\pagebreak
\subsection[Classes PHP5]{Class Structure PHP5}\label{sec:classes}
\begin{lstlisting}
class <className> [<extends baseClass>]
{ [<modifiers*>] [<class member variables>];
  [<modifiers*>] function <functionName>([<parameters>]){
    <statements>;
    parent::function() # call from parent class
    self::function() # call within class itself
  }# end function
}# end class
### *modifiers used in PHP5:
public # can be 'seen' everywhere
protected # limits access to inherited and parent classes
private # limits visibility only to the class
static # is static, i.e. not changable
(*\info{Because static methods are callable without an instance of the object created, the pseudo variable \texttt{\$this} is not available inside the method declared as static. Static properties cannot be accessed through the object using the arrow operator \texttt{->}.}*)
final # prevents child classes from overriding a method
interface # a class with no data members, contains only member functions
\end{lstlisting}
\begin{lstlisting}[style=exampleblock]
(*\example*) interface employee{
  function setData($empName,$empAge);
  function outputData();}
class payment implements employee{
  function setData($empName,$empAge) {/* Functionality */}
  function outputData()  { echo "Inside payment Class";}
}# end class payment
\end{lstlisting}
\begin{lstlisting}
abstract /* defines the basic skeleton for the class, contains attributes and methods changed/used by an extended class */
\end{lstlisting}

\subsubsection{Declare/Use}
\begin{lstlisting}
(*\obj*) $objName = new className([<construnctor>]);
(*\obj*) $objNameSibling = clone $objName; # a clone
(*\mixed*) $objName->funcName(); # call to class function
(*\obj*) $objAssigned   =  $objName;
(*\obj*) $objReference  =& $objName; # reference = same content
(*\mixed*) className::funcName(); # Static call without instance
/* changing variables */
  $objName->var = '$objAssigned will have this value';
  $objName = null; # $instance and $reference become null
\end{lstlisting}
\begin{lstlisting}[style=exampleblock]
(*\example*) class SimpleClass{# declarations
  public $var = 'a default value';
  // private $var4 = self::myStaticMethod();
  public function displayVar() {
    echo $this->var; # show the within-class value
  }// end method displayVar
}// end SimpleClass
$objName = new SimpleClass();
$objName->displayVar();# 'a default value'
$objName->var='another value';
$objName->displayVar();# 'another value'
var_dump($objName); # ask for infos
# object(SimpleClass)(*\ttfamily\#*)1 (1) {
#  ["var"]=>
#  string(13) "another value"
# }
(*\example*) ### call another class statically with ::
class A{# (*\comment from \href{http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php#84155}{http://www.php.net/manual/en/}*)
  public function TestFunc(){
    return $this->test." to call ".__CLASS__;}
}# end class A()
class B{
  public $test;
  public function __construct(){
    $this->test = "Nice trick from ".__CLASS__;}
  public function GetTest(){return A::TestFunc();}
}# end class B()
$objB = new B;
echo $objB->GetTest(); # Nice trick from B to call A
\end{lstlisting}

\subsubsection[Store/Recover]{Store/Recover Obj.}
\begin{lstlisting}[style=exampleblock]
(*\example*) ### serialize objects -> storable strings
class test{public $var = 'Variable';}
  echo serialize(new test());
// O:4:"test":1:{s:6:"strVar";s:8:"Variable";}
(*\example*) ### unserialize (restore) objects with its properties
$strObj = 'O:4:"test":1:{s:6:"strVar";s:8:"Variable";}';
$obj = unserialize($strObj);
echo $obj->strVar;# Variable
(*\example*) ### serialize but clean a objects __sleep()
class SerializeTest {
  public $var  = 'Variable';
  public $var1 = 'Variable 1';
  private $resource = 'Resource id #1'; //a ressource
  function __sleep() {#saves $var & $var1, not ressource
    return array('var', 'var1'); # must be array!!
    /* return get_object_vars($this); */
    /* for all variables ^^^ instead */}
}# end class SerializeTest()
$objSerialize = new SerializeTest();
echo serialize($objSerialize); #call to  __sleep()
#O:13:"SerializeTest":2:{s:3:"var";s:8:"Variable";s:4: "var1";s:10:"Variable 1";}
(*\info{In \texttt{\_\_sleep()} was specified, to save only \texttt{\$var} and \texttt{\$var1} to be saved for a subsequent access.}*)
(*\example*) ### unserialize and restore things  __wakeup()
class SerializeTest{
  public $var  = 'Variable'; public $var1 = 'Variable 1';
  private $resource = 'Resource id #1';
  function __sleep()
    {return array('resource');/* save only $resource */}
  function __wakeup()
    {echo 'Connect for instance to DB '.$this->resource;}
}# end class SerializeTest()
\end{lstlisting}

\subsubsection{Magic Functions}

\begin{lstlisting}[style=exampleblock]
(*\example*) ### __autoload() automatically done or loaded
# anywhere before the classes:
function __autoload($className)
  {require_once '/pathToClass/'.$className.'.inc';}
$obj =new MyClass1();# loads '/pathToClass/MyClass1.inc'
$obj2=new MyClass2();# loads '/pathToClass/MyClass2.inc'
(*\example*) ### __construct: automatically at initiation
class greetings{ # automatically at initiation:
  function __construct($name) {echo "Hello $name!";}
}# end class greetings()
$objGreet = new greetings("Robert"); # Hello Robert!
(*\example*) ### __destruct: automatically at termination
class MyDestructableClass{
  public $name;
  function __construct() {
      print "In constructor done\n";
      $this->name = "MyDestructableClass";}
  function __destruct() {
    print "While destroying " . $this->name . "\n";}
}# end class MyDestructableClass()
$obj = new MyDestructableClass(); # 'In constructor done'
unset($obj); # While destroying MyDestructableClass
\end{lstlisting}
\begin{lstlisting}
### __clone() identical copy of objects
/* clone objects with 'clone': */
  $copy_of_object = clone $object;
/* or explicit in called method __clone() detailed */
\end{lstlisting}
\begin{lstlisting}[style=exampleblock]
(*\example*) class Animal{# (*\comment from \href{http://www.hiteshagrawal.com/php/php5-magic-methods/}{http://www.hiteshagrawal.com/}*)
  public $name; public $legs;
  function setName($name){ $this->name = $name; }
  function setLegs($legs){ $this->legs = $legs; }
  function __clone()
    { echo "<br>Object Cloning in Progress"; }
}# end class Animal()
$tiger = new Animal(); $tiger->name = "Tiger";
$tiger->legs = 4; $kangaroo = clone $tiger;
echo "<br>".$kangaroo->name."---".$kangaroo->legs;
  // Tiger---4 (here identical)
$kangaroo->name = "Kangaroo"; $kangaroo->legs = 2;
echo "<br>".$tiger->name."---".$tiger->legs;
echo "<br>".$kangaroo->name."---".$kangaroo->legs;
  // Object Cloning in Progress
  // Tiger---4
  // Kangaroo---2 (here now modified)
\end{lstlisting}
\begin{lstlisting}
### __toString() returns a string from an object
function __toString()
  { /*... statements */}
(*\info{In PHP5 get called while trying to print or echo the class objects. This method can be used print all the methods and attributes defined for the class at runtime for debugging. Also this method can be used to give error message while somebody tries to print the class details (\href{http://www.hiteshagrawal.com/php/php5-magic-methods/}{http://www.hiteshagrawal.com/}).}*)
### __unset() check for clear an undeclared data member
function __unset($var){
   /* $var is a Variable that unset is supposed to check. Error message or error-handling can be putted here. */}
### __isset() check for undeclared data member
function __isset($var){
   /* $var is a Variable that isset is supposed to check. Error message or error-handling can be putted here. */}
### __get() check for undeclared or undefined attributes
function __get($var){
   /* $var is a Variable that checked, if able to get. Error message or error-handling can be putted here. */}
### __set() check for undeclared or undefined attributes
function __set($data,$value)
  {/* $data - holds the name of the undefined attributes. $value - holds the value assigned to the undefined attributes. */}
### __call() check for undefined methods ###
function __call($data,$argument)
  { /* $data holds the name of the undefined method getting called. $argument holds the argument passed to the method. */ }
\end{lstlisting}

\end{multicols}

%  \printindex
\end{document}


