Objektorientierung
<?php class ClassName {
public $public_member_var;
private $private_member_var;
public function publicMemberFunc() {
$this->privateMemberFunc($this->private_member_var);
self::privateMemberFunc($this->private_member_var);
}
private function privateMemberFunc($param) {
$this->public_member_var = $param;
}
}
?>
<?php class Person {
public $name;
function __construct($name = 'Unbekannt') {
$this->name = $name;
$this->me('hallo');
}
function __destruct() { $this->me('auf Wiedersehen'); }
function me($text = '') { echo "{$this->name} sagt $text.\n"; }
}
?>
<?php
$anon = new Person; // Unbekannt sagt hallo.
$bob = new Person('Bob'); // Bob sagt hallo.
$bob->alter = strlen($bob->name) * 8; // 24
$bob->me(", er sei {$bob->alter} Jahre alt");
unset($bob); // Bob sagt auf Wiedersehen.
$anon instanceof Person; // true
?>
<?php class Math {
static function isPrime($num) {
if ($num == 2) return true;
if ($num == 1 || $num % 2 == 0) return false;
for ($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2)
if ($num % $i == 0) return false;
return true;
}
}
Math::isPrime(2147483647); // true
?>
Quelle: Stack Overflow
<?php class Basis {
private $price = 100;
function getPrice() { return $this->price; }
}
class Premium extends Basis {
function getPrice() { return parent::getPrice() * 2; }
}
(new Basis)->getPrice(); // 100
(new Premium)->getPrice(); // 200
?>
<?php
interface iTemplate {
public function setVariable($name, $var);
public function getHtml($template);
}
class Template implements iTemplate {
public function setVariable($name, $var) { ... }
public function getHtml($template) { ... }
}
interface iSpecialTemplate extends iTemplate { ... }
?>
<?php
namespace htw\beier\beispiele;
function foo() { echo 'Hmm'; }
?> … woanders … <?php
echo htw\beier\beispiele\foo(); // uargs
use htw\beier\beispiele as bsp;
echo bsp\foo();
use htw\beier\beispiele\foo;
echo foo();
?>
<?php
try {
echo "Moin\n";
throw new Exception('Ich bin eine Fehlermeldung.');
echo 'Ich werde nie ausgeführt.';
} catch (Exception $e) {
echo "Exception gefangen: {$e->getMessage()}\n";
} finally {
echo "Mir doch egal.\n";
}
echo "War was?\n";
?>
__construct()
,
__destruct()
,
__call()
,
__callStatic()
,
__get()
,
__set()
,
__isset()
,
__unset()
,
__sleep()
,
__wakeup()
,
__toString()
,
__invoke()
,
__set_state()
,
__clone()
,
__debugInfo()
<?php // meh
require_once 'classes/Basis.php';
require_once 'classes/Premium.php';
$angebot = new Premium;
?>
<?php // ahhh
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.php';
});
?>