2011-07-12 52 views
-1

我有一個PHP類的定義,使用所有典型的數據庫方法(Crud,等等)稱爲databaseObject的類。我最近改變了我的數據庫結構,以便每個表中的id列不再被稱爲「id」,現在無論表格中保存了id + id(例如:Companies Table的ID爲「companyId」)。因此,現在在擴展databaseObject的類中,我包含一個名爲$ table_id的靜態變量,該變量保存該表的id的名稱。現在我需要調用該類變量時遇到了一種情況。示例代碼如下。此代碼正在PHP 5.3中運行。調用一個變量的PHP類變量

//databaseObject Delete Method; 
public function delete() { 
    global $database; 
    //DELETE FROM table WHERE condition LIMIT 1 
    //escape all values to prevent SQL injection 
    // - use LIMIT 1 
    $sql = "DELETE FROM ".static::$table_name; 
    $sql .= " WHERE ".static::$table_id."=". $database->escape_value($this->id); 
    $sql .= " LIMIT 1"; 
    $database->query($sql); 
    return ($database->affected_rows() ==1) ? true : false; 
} 

//Actual Class that creates the issue 
require_once(LIB_PATH.DS.'database.php'); 
require_once(LIB_PATH.DS.'databaseobject.php'); 

class Contact extends DatabaseObject { 
    protected static $table_name="contacts"; 
    protected static $table_id="contactId"; 
    protected static $db_fields = array('contactId','companyId','contactName', 'phone', 'fax', 'email'); 
    public $contactId; 
    public $companyId; 
    public $contactName; 
    public $phone; 
    public $fax; 
    public $email; 
} 

//Code that calls the method 
$contact = Contact::find_by_id($_GET['contactId']); 
if($contact && $contact->delete()) { 
    $session->message("The Contact was deleted."); 
    log_action('Contact Deleted', "Contact was deleted by User ID {$session->id}"); 
    redirect_to("../companies/viewCompany.php?companyId={$contact->companyId}");  
} else { 
    $session->message("The Contact could not be deleted"); 
    redirect_to('../companies/listCompanies.php'); 

}

+0

那麼自我呢? – ComFreek

+0

我不認爲這是問題。他已經有了靜態成員,所以我認爲他已經知道如何與他們合作。我敢打賭,現在他問的是如何訪問在$ table_id中的名字的類字段。這是有道理的。 – AlexanderMP

回答

3

使用self::$variablestatic::$variable

+0

爲什麼?請閱讀這裏的文檔:http://php.net/manual/en/language.oop5.static.php並回應,在這種情況下爲什麼是靜態::不正確? – AlexanderMP

-2

你需要的是Reflection

class Foo { 
    protected $bar = 'barrr!'; 
    private $baz = 'bazzz!'; 
} 

$reflFoo = new ReflectionClass('Foo'); 
$reflBar = $reflFoo->getProperty('bar'); 
$reflBaz = $reflFoo->getProperty('baz'); 

// Set private and protected members accessible for getValue/setValue 
$reflBar->setAccessible(true); 
$reflBaz->setAccessible(true); 

$foo = new Foo(); 
echo $reflBar->getValue($foo); // will output "barrr!" 
echo $reflBaz->getValue($foo); // will output "bazzz!" 

// You can also setValue 
$reflBar->setValue($foo, "new value"); 
echo $reflBar->getValue($foo); // will output "new value" 

Contract::$table_id訪問字段名稱,並獲得價值contractId。所以如果我理解正確,你想得到$contract->contractId,但是名字contractId是由在此之前執行的代碼決定的。

這是反射派上用場的地方。