![]() |
![]() |
![]()
Post
#1
|
|
Grupa: Zarejestrowani Postów: 204 Pomógł: 0 Dołączył: 26.12.2003 Skąd: Rzeszów Ostrzeżenie: (0%) ![]() ![]() |
Może mnie ktoś oświecić dlaczego używa się singletonów? np:
skoro to samo można osiągnąć w ten sposób?:
Widze jakie są różnice, jednak nie rozumiem dlaczego singletony są stosowane skoro zapis Foo::bar(); jest wygodniejszy i kod klasy krótszy... Czy za pomocą singletonów można zrobić coś, o czym nie wiem? |
|
|
![]() |
![]()
Post
#2
|
|
Grupa: Zarejestrowani Postów: 204 Pomógł: 0 Dołączył: 26.12.2003 Skąd: Rzeszów Ostrzeżenie: (0%) ![]() ![]() |
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] :?: |
|
|
![]() ![]() |
![]() |
Aktualny czas: 9.10.2025 - 05:42 |