PHP-Snippets
Eine Snippet-Sammlung für PHP.
Grundlagen
// Null-Prüfung
if (isset($bla)) ...
// Leer-Prüfung
assert(empty(25) == FALSE);
assert(empty("bla") == FALSE);
assert(empty(NULL) == TRUE);
assert(empty(FALSE) == TRUE);
assert(empty("") == TRUE);
assert(empty(array()) == TRUE);
assert(empty(0) == TRUE);
assert(empty("0") == TRUE);
var $notUsed;
assert(empty($notUsed) == TRUE);
Datenstrukturen
Normales Array iterieren:
$arr = array("one", "two", "three", "four", "five");
// Einfach
foreach ($arr as $item) {
echo $item;
}
// Mit Zähler
for ($i = 0; $i < count($arr); $i++) {
echo $arr[$i];
}
Assoziatives Array iterieren:
$map = array(
"one" => 1,
"two" => 2,
"three" => 3,
"blubb" => 17
);
foreach ($map as $key => $value) {
echo "$key => $value\n";
}
Array-Gewurschtel:
// Hinzufügen
$arr = array();
$arr[] = "new item";
$map = array();
$map["new key"] = "new value";
// Entfernen
unset($map["akey"]);
Strings
Escaping:
assert(stripslashes('Ein \\"echter\\" Teppich') == 'Ein "echter" Teppich');
Multiline Strings:
// Einfach:
$str = 'Dies
ist ein
Multiline-String
';
// Mit speziellem Ende-Token:
$str = <<TO_END;
Dies
ist ein
Multiline-String
TO_END;
JSON-Decoding:
$data = json_decode($_REQUEST["data"]);
Mehrfache Ersetzungen:
function escapeJsString($str) {
$ptrnArr = array();
$replArr = array();
$ptrnArr[] = "/'/"; $replArr[] = "\\'";
$ptrnArr[] = "/\n/"; $replArr[] = "\\n";
$ptrnArr[] = '/"/'; $replArr[] = """;
return preg_replace($ptrnArr, $replArr, $str);
}
Fehlerbehandlung
try {
throw new Exception("Das war wohl nix");
} catch (Exception $exc) {
echo __METHOD__ . " - Something went wrong: " . $exc->getMessage()
."\nat " . $exc->getFile() . "(" . $exc->getLine() . ")"
."\n" . $exc->getTraceAsString();
throw new Exception("Outer exception", 0, $exc);
}
Details zur Exception-Klasse.
Objekt-Orientierung
class MyClass extends MySuperClass {
// Konstanten
public static const $someName = "Hallo";
// Members
var $color = "red";
private $blaber;
// Static members
protected static $kruscht;
// Konstruktor - Alternative 1
function __construct($bli, $blaber = 25) {
$this->blaber = $blaber;
echo self::$someName;
}
// Konstruktor - Alternative 2
function MyClass($bli, $blaber = 25) {
$this->blaber = $blaber;
}
// Destruktor
function __destruct() {
...
}
// Methoden
function __toString() {
return ...;
}
public function doIt() {
$this->doThat();
}
function doThat() {
...
}
// Static methods
public static function bla() {
...
}
}
Reflection:
// Get the class name of an object
echo get_class($obj);
HTTP-Request / -Response-Verarbeitung
Request-Body lesen:
$reqBody = @file_get_contents('php://input');
XML-Verarbeitung
DOM-Gewurschtel: FIXME Statt simplexml lieber DOMDocument verwenden. Es hat eine viel bessere API und geht korrekt mit Encodings um.
$dom = simplexml_load_file("myfile.xml");
$someElems = $dom->xpath("/someelem");
foreach($someElems as $someElem) {
$subXpathQuery = $someElem->xpath("/somesubelem");
$attr = $someElem->attributes();
$attribBla = (string) $attr["bla"];
$text = (string) $someElem[0];
}
XSLT:
$xsl = new XSLTProcessor();
$doc = new DOMDocument();
$xsl->setParameter("", "param-name-1", "param-value-1");
$xsl->setParameter("", "param-name-2", "param-value-2");
$doc->load("stylesheet.xsl");
$xsl->importStyleSheet($doc);
$doc->loadXML("source.xml");
$result = $xsl->transformToXML($doc);