PHP: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
(7 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt) | |||
Zeile 6: | Zeile 6: | ||
* [[WinNMP]] | * [[WinNMP]] | ||
* [[PHP-Beispiele]] | * [[PHP-Beispiele]] | ||
* [https://www.php.net/manual/en/function.strrpos.php PHP-Funktionsreferenz] | |||
== Besonderheiten == | == Besonderheiten == | ||
Zeile 54: | Zeile 55: | ||
=== Datum/Zeit === | === Datum/Zeit === | ||
<pre>$date = date_create_from_format('d.m.Y H:i', '1.2.2018 17:14'); | <pre> | ||
$date = date_create_from_format('d.m.Y H:i', '1.2.2018 17:14'); | |||
$year = intval(date('Y')); | |||
$date2 = new DateTime("2012-07-08 11:14:15.638276"); | $date2 = new DateTime("2012-07-08 11:14:15.638276"); | ||
assert($date2 < $date); | |||
$timestamp2 = time(); | $timestamp2 = time(); | ||
Zeile 76: | Zeile 82: | ||
$date->add(new DateInterval('PT86400S')); // 86400 sec | $date->add(new DateInterval('PT86400S')); // 86400 sec | ||
$date->add(new DateInterval('P10D'); // 10 Tage | $date->add(new DateInterval('P10D')); // 10 Tage | ||
$firstSecondOfMonth = mktime(0, 0, 0, date("n"), 1); // Unix Timestamp | $firstSecondOfMonth = mktime(0, 0, 0, date("n"), 1); // Unix Timestamp | ||
$lastMinuteOfMonth = mktime(23, 59, 59, date("n"), date("t")); // Unix Timestamp | $lastMinuteOfMonth = mktime(23, 59, 59, date("n"), date("t")); // Unix Timestamp | ||
$dayOfWeek = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][\DateTime()->format('w'); | |||
</pre> | </pre> | ||
Zeile 141: | Zeile 147: | ||
</pre> | </pre> | ||
== Exceptions == | |||
<syntaxhighlight lang="php"> | |||
try { | |||
echo inverse(5) . "\n"; | |||
echo inverse(0) . "\n"; | |||
} catch (Exception $e) { | |||
echo 'Exception abgefangen: ', $e->getMessage(), "\n"; | |||
} finally { | |||
echo "Erstes finally.\n"; | |||
} | |||
</syntaxhighlight> | |||
== Metaprogrammierung == | == Metaprogrammierung == | ||
* string gettype($mixed), is_integer(), is_object(), is_bool(), is_array() isset() ... | * string gettype($mixed), is_integer(), is_object(), is_bool(), is_array() isset() ... | ||
Zeile 146: | Zeile 163: | ||
* if ($var instanceof ExampleClass) {} | * if ($var instanceof ExampleClass) {} | ||
* if (method_exists ( $this , 'do_it' ){ call_user_func(array($this, 'do_it')); } | * if (method_exists ( $this , 'do_it' ){ call_user_func(array($this, 'do_it')); } | ||
<syntaxhighlight lang="php"> | |||
$obj = new Foo(); | |||
$classStr = 'Foo'; | |||
$methodStr = 'method'; | |||
$staticmethodStr = 'staticmethod'; | |||
$f1 = strlen(...); | |||
$f2 = $obj(...); // invokable object | |||
$f3 = $obj->method(...); | |||
$f4 = $obj->$methodStr(...); | |||
$f5 = Foo::staticmethod(...); | |||
$f6 = $classStr::$staticmethodStr(...); | |||
// traditional callable using string, array | |||
$f7 = 'strlen'(...); | |||
$f8 = [$obj, 'method'](...); | |||
$f9 = [Foo::class, 'staticmethod'](...); | |||
</syntaxhighlight> | |||
= Wichtige Funktionen = | = Wichtige Funktionen = | ||
Zeile 186: | Zeile 223: | ||
assert($matcher[0] [2] [1] === '2'); | assert($matcher[0] [2] [1] === '2'); | ||
assert($matcher[0] [2] [2] === '3'); | assert($matcher[0] [2] [2] === '3'); | ||
$line = preg_replace_callback('|<p>\s*\w|', | |||
function ($matches) { | |||
return strtolower($matches[0]); | |||
}, $line); | |||
</pre> | </pre> |
Aktuelle Version vom 8. Juni 2024, 16:21 Uhr
Links[Bearbeiten]
Besonderheiten[Bearbeiten]
- Assignment von Objekten speichert Kopie. Aber möglich Referenzzuweisung: $obj2 = &$obj;
Anweisungen[Bearbeiten]
- switch() erlaubt Strings als Marken.
- continue im switch ist wie break.
- continue <level>: springt aus verschachtelten Statements (Schleifen + Switch)
Typen[Bearbeiten]
- Konvertierungen: string strval($expr) und integer intval($expr)
Arrays[Bearbeiten]
- sequentiell oder assoziativ:
- $a = array(1, 2); $b = array("a" => 1, "b" => 55);
- ab 5.4: $a = [1, 2]; $b = ["a" => 1, "b" => 55];
- Test: array_key_exists($array, $key) oder isset($arr[$key])
- $ix = array_search(2, $a);
- $key = array_search(55);
- array_push($array, $value) hängt an...
- count($arr) zählt Elemente (flach) oder rekursiv: count($arr, COUNT_RECURSIVE)
- Test: is_array()
- Löschen: unset($array['index']);
Strings[Bearbeiten]
- 'string' kennt nur 2 ESC-Zeichen: \' und \\: 'Geht\'s wieder' 'c:\\windows'
- "string" kennt alle C-ESC-Zeichen ('\t'...) und Variablenexpansion: "$path/$node"
Stringformatierung[Bearbeiten]
sprintf("%3.3f", $number);
Klassen[Bearbeiten]
- Konstruktor der Basisklasse aufrufen:
class Demo extends BaseDemo { function __construct($name){ parent::__construct ( $name ); } }
- abstrakte Klassen:
abstract class AbstractClass { abstract protected function getValue(); }
Datum/Zeit[Bearbeiten]
$date = date_create_from_format('d.m.Y H:i', '1.2.2018 17:14'); $year = intval(date('Y')); $date2 = new DateTime("2012-07-08 11:14:15.638276"); assert($date2 < $date); $timestamp2 = time(); $timestamp = 1170288000; // a timestamp $date4 = new DateTime("@$timestamp"); $date3 = new \DateTime(); $date3->setDate($year, $month, $day); $date3->setTime($hour, $minute, $second); $unixTimestamp = $date->getTimestamp(); $string = $date->format('d.m.Y H:i.s'); $stringFromTimestampYesterday = \date('d.m.Y', \time() - 86400); $diff = $date2 - $date1; $date->add($diff); $date->add(new DateInterval('PT86400S')); // 86400 sec $date->add(new DateInterval('P10D')); // 10 Tage $firstSecondOfMonth = mktime(0, 0, 0, date("n"), 1); // Unix Timestamp $lastMinuteOfMonth = mktime(23, 59, 59, date("n"), date("t")); // Unix Timestamp $dayOfWeek = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][\DateTime()->format('w');
Lambda-Ausdrücke[Bearbeiten]
$input = array(1, 2, 3, 4, 5); $output = array_filter($input, function ($v) { return $v > 2; });
Dateien[Bearbeiten]
if ( ($fp = fopen($filename, "r")) != null){ while ( ($line = fgets ($fp, 8192)) != null){ echo $line; } fclose($fp); }
Traits[Bearbeiten]
Traits sind "Copy-Paste"-Klassenkonstruktionen, die anstatt von Mehrfachvererbung eingesetzt werden können.
- Keine Instantiierungen
- Statische Elemente sind in jeder Anwendungsklasse extra instantiiert.
- Ausblenden/Umbenennen von Methoden möglich.
Definition: trait ExampleTrait {
function doIt(){}
} Benutzung:
class Example { use ExampleTrait; }
Konfliktauflösung und Methoden-Umbenennung:
trait A { public function smallTalk() { echo 'a'; } public function bigTalk() { echo 'A'; } } trait B { public function smallTalk() { echo 'b'; } public function bigTalk() { echo 'B'; } } class Talker { use A, B { B::smallTalk insteadof A; A::bigTalk insteadof B; B::bigTalk as talk; } }
Generatoren[Bearbeiten]
Wie in Python: Einfache Umsetzung von iterierbaren Objekten.
function oneTwoThree() { for ($i = 1; $i <= 3; $i++) { yield $i; } } foreach (oneTwoThree() as $val) { print $val; }
Exceptions[Bearbeiten]
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Exception abgefangen: ', $e->getMessage(), "\n";
} finally {
echo "Erstes finally.\n";
}
Metaprogrammierung[Bearbeiten]
- string gettype($mixed), is_integer(), is_object(), is_bool(), is_array() isset() ...
- gettype() returns "string", "integer", "NULL", ...
- if ($var instanceof ExampleClass) {}
- if (method_exists ( $this , 'do_it' ){ call_user_func(array($this, 'do_it')); }
$obj = new Foo();
$classStr = 'Foo';
$methodStr = 'method';
$staticmethodStr = 'staticmethod';
$f1 = strlen(...);
$f2 = $obj(...); // invokable object
$f3 = $obj->method(...);
$f4 = $obj->$methodStr(...);
$f5 = Foo::staticmethod(...);
$f6 = $classStr::$staticmethodStr(...);
// traditional callable using string, array
$f7 = 'strlen'(...);
$f8 = [$obj, 'method'](...);
$f9 = [Foo::class, 'staticmethod'](...);
Wichtige Funktionen[Bearbeiten]
- $mixed print_r($var, $doReturnString = false) gibt menschenlesbare Form der Variablen aus oder liefert diese als String
$stack = debug_backtrace(); $fp = fopen("/tmp/wp.trace", "a"); fwrite($fp, "---------\n" . $location . "\n"); foreach ($entry as $stack){ $args = ""; foreach ($entry["args"] as $arg){ $args .= " " . strval($arg); } $line = $entry["function"] . " " . $entry["file"] . ":" . $entry["line"] . " " . $args . "\n"; fwrite($fp, $line); } fclose($fp);
Reguläre Ausdrücke[Bearbeiten]
if (preg_match('/id=(\d+)/', "id=222 name=Hans", $match)){ $id = $match[1]; $assignment = $match[0]; assert($id == 222); assert ($assignment === "id=222"); } preg_match('!/dev/(\w+)!, "/dev/sda1", $matcher); assert($matcher[1] === 'sda1'); preg_match_all('/(\w+)=(\d+)/', 'a=1 b=2 c=3', $matcher); assert($matcher[0] [0] [0] === 'a=1'); assert($matcher[0] [0] [1] === 'b=2'); assert($matcher[0] [0] [2] === 'c=3'); assert($matcher[0] [1] [0] === 'a'); assert($matcher[0] [1] [1] === 'b'); assert($matcher[0] [1] [2] === 'c'); assert($matcher[0] [2] [0] === '1'); assert($matcher[0] [2] [1] === '2'); assert($matcher[0] [2] [2] === '3'); $line = preg_replace_callback('|<p>\s*\w|', function ($matches) { return strtolower($matches[0]); }, $line);