PHP 5.2 Abstract Singletons: “abstract public static function” issue

Ein Problem über das ich schon häufiger gestolpert bin ist folgendes: Man will aus irgeneinem Grund eine abstrakte Singleton-Klasse definieren, sprich alle abgeleiteten Klassen sollen nur jeweils einmal instanziert werden.

In PHP 5.3 dank late static binding sehr einfach lösbar: Beispiel

In vorherigen Versionen ist es auf diese Weise nicht lösbar, die naive Herangehensweise wäre daher so etwas:

abstract class AbstractSingleton
{
	protected function __construct() { }
	private function __clone() { }
	abstract public static function getInstance();
}
class ConcreteSingleton extends AbstractSingleton
{
	private static $instance;
	public static function getInstance()
	{
		if (empty(self::$instance)) {
			self::$instance = new ConcreteSingleton();
		}
		return self::$instance;
	}
}

was jedoch seit PHP 5.2 berechtigerweise einen E_STRICT Fehler wegen “abstract static” wirft.
Continue reading “PHP 5.2 Abstract Singletons: “abstract public static function” issue”

PHP Fatal Error Handler

Codeschnipsel inspiriert von diesem Artikel:

fatalerrorhandler.php

<?php
// report all but fatal errors 
error_reporting((E_ALL | E_STRICT) ^ (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR));

// fatal error handler as shutdown function
register_shutdown_function('fatalErrorHandler'); 

function fatalErrorHandler() {
	$error = error_get_last();
	if ($error['type'] & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR)) {
		echo '<h1>Fatal Error, shutting down...</h1>';
		echo '<pre>' . var_export($error,true) . '</pre>';
	} else {
		echo 'Regular Shutdown, no fatal errors.';
	}
}

test1.php

<?php
require 'fatalerrorhandler.php';

// Fatal Error (E_ERROR)
unknown_function_call();

test2.php

<?php
require 'fatalerrorhandler.php';

// E_USER_ERROR
trigger_error('...', E_USER_ERROR);

test3.php

<?php
require 'fatalerrorhandler.php';

// Notice (E_NOTICE)
echo $unknown_var;