z tym się zgodzę, bo sam używam takiego rozwiązania, jednak dalej nie daje mi to spokoju.
cytat z
http://www.phppatterns.com/index.php/artic...icleview/6/1/1/
Cytat
But first we have to overcome a small problem in php - the lack of static class variables (something that's coming in the Zend 2 engine)
[php:1:9bafc4226a]<?php
// A generic function to create and fetch static objects
function staticInstance($class) {
// Declare a static variable to hold the object instance
static $instance;
// If the instance is not there, create one
if(!isset($instance)) {
$instance =& new $class;
}
return($instance);
}
?>[/php:1:9bafc4226a]
Co jeśli klasa wygląda np tak:
[php:1:9bafc4226a]<?php
final class Temp {
private static $content;
public static function add($content) {
self::$content.= $content;
}
public static function get() {
return self::$content;
}
public static function clear() {
self::$content = '';
}
}
?>[/php:1:9bafc4226a]
Czy to też trzeba używać singletonu?
Nie lepiej jest właśnie tak?
Podobnie może wyglądać klasa do ubsługi bazy danych.
Na przykład:
[php:1:9bafc4226a]<?php
class SQL {
private static $conn;
private static $result = array();
public static function connect($host, $user, $pass, $db) {
self::$conn = @mysql_connect($host, $user, $pass);
if (!self::$conn || !@mysql_select_db($db, self::$conn)) {
trigger_error(mysql_error(), E_ERROR);
}
}
public static function query($query, $label = 'default') {
$result = @mysql_query($query, self::$conn);
if(!$result) {
trigger_error(mysql_error(), E_ERROR);
} else {
self::$result[$label] = $result;
}
}
itd...
?>[/php:1:9bafc4226a]
Nie lepiej używać:
[php:1:9bafc4226a]<?php
SQL::query('SELECT name FROM ...');
while($row = SQL::fetchArray()) {
print $row['name'];
}
?>[/php:1:9bafc4226a]
niż np:
[php:1:9bafc4226a]<?php
$sql = SQL::getRef();
$sql->query('SELECT name FROM ...');
while($row = $sql->fetchArray()) {
print $row['name'];
}
?>[/php:1:9bafc4226a]
:?: