Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> słowa kluczowe parent, self.. brakuje mi jednego :)
Nalfein][WR
post
Post #1





Grupa: Zarejestrowani
Postów: 66
Pomógł: 0
Dołączył: 22.04.2003
Skąd: Żory / K-ce

Ostrzeżenie: (0%)
-----


[php:1:9afb1fe096]
class AbstractSingleton
{
static function instance()
{
static $instance;
if (!$instance)
{
// nie mogę napisać $this, bo metoda jest statyczna
$class = self::getClassName();
$instance = new $class;
}
return $instance;
}



}


class test extends AbstractSingleton
{
function getClassName() {
return 'test'; // edit: skądś tutaj wziąłem 'test2'
}
}

test::instance();
[/php:1:9afb1fe096]

wywala błąd:

Fatal error: Call to undefined method abstractsingleton::getclassname() in E:usrwwwssiindex.php on line 12

Testowałem na PHP5 b2 i b3, z i bez słowa kluczowego "static" na początku metody. Podmieniałem self na $this, this i bez skutku.

Niby dobrze, bo self:: służy do wywołania metody klasy w której jestem, używa się jej przy nadpisywaniu. Wobec tego jakiego słowa mam użyć zamiast "self", jest jakiś odpowiednik $this bez "$" do użycia w metodach statycznych?
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
Nalfein][WR
post
Post #2





Grupa: Zarejestrowani
Postów: 66
Pomógł: 0
Dołączył: 22.04.2003
Skąd: Żory / K-ce

Ostrzeżenie: (0%)
-----


Póki co wymyśliłem protezę, podaję w razie czego:

[php:1:2d17acddaf]
class AbstractSingleton
{
function instance($class) {
static $instance;
if (!$instance) $instance = new $class;
return $instance;
}

}

class test extends AbstractSingleton
{
function instance($class = '') {
return parent::instance($class ? $class : 'test');
}
}

class test2 extends test
{
function instance($class = '') {
return parent::instance($class ? $class : 'test2');
}
}

assert(is_a(test::instance(), 'test'));
[/php:1:2d17acddaf]

Niewiele mniej pisania, ale działa dobrze.
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 8.10.2025 - 13:36