2009-05-16 6 views
4

Hier ist meine Situation: Ich habe eine PHP-Basisklasse haben, die etwa wie folgt aussieht:PHP 5.2 Virtuelle-wie statische Methoden

class Table { 
    static $table_name = "table"; 
    public function selectAllSQL(){ 
    return "SELECT * FROM " . self::$table_name; 
    } 
} 

Und eine Unterklasse, die wie folgt lautet:

class MyTable extends Table { 
    static $table_name = "my_table"; 
} 

Leider wenn ich tun:

MyTable::selectAllSQL() 

ich:

"SELECT * FROM table" 

statt meinem gewünschten Ergebnis,

"SELECT * FROM my_table" 

Es sieht aus wie dies in php erreicht werden kann 5.3 late static bindings verwenden, aber ist es eine Möglichkeit, dieses Verhalten in PHP 5.2.x erreichen kann?

Antwort

0

Wäre es eine Option, die Klassen zu instanziieren?

+0

Leider nein :( –

3

Nicht wirklich. Deshalb wurde LSB zu 5.3 hinzugefügt. Instantiation ist der Weg zu gehen, an diesem Ort, zusammen mit einem Singleton.

1

Instanziieren Sie die Klasse der Ursache ist eine Option!

<?php 
abstract class Table { 
    protected $table_name; 
    public function selectAllSQL() { 
     return 'SELECT * FROM ' . $this->table_name; 
    } 
} 

class MyTable extends Table { 
    protected $table_name = 'my_table'; 
} 

$my_table = new MyTable(); 
echo $my_table->selectAllSQL(); // Will output "SELECT * FROM my_table" 

Wenn Sie als Neuimplementierung statisch zu halten haben, ist der einzige Weg, in PHP gehen < 5.3:

<?php 
abstract class Table { 
    protected static $table_name = 'table'; 
    public static function selectAllSQL() { 
     return self::selectAllSQLTable(self::$table_name); 
    } 
    public static function selectAllSQLTable($table) { 
     return 'SELECT * FROM ' . $table; 
    } 
} 

class MyTable extends Table { 
    protected static $table_name = 'my_table'; 
    public static function selectAllSQL() { 
     return self::selectAllSQLTable(self::$table_name); 
    } 
} 

class MyOtherTable extends Table { 
    protected static $table_name = 'my_other_table'; 
    public static function selectAllSQL() { 
     return self::selectAllSQLTable(self::$table_name); 
    } 
} 

echo MyTable::selectAllSQL(); // Will output "SELECT * FROM my_table" 
echo MyOtherTable::selectAllSQL(); // Will output "SELECT * FROM my_other_table" 
2

Yeh spät statisch ist die Art und Weise verbindlich zu gehen. Vielleicht sind Sie jetzt auf PHP 5.3. Hier ist, wie es dann aussehen sollte:

ändern

class Table { 
    static $table_name = "table"; 
    public function selectAllSQL(){ 
    return "SELECT * FROM " . self::$table_name; 
    } 
} 

zu

class Table { 
    static $table_name = "table"; 
    public function selectAllSQL(){ 
    return "SELECT * FROM " . static::$table_name; 
    } 
} 
+0

Es ist Arbeit für mich –