2011-07-12 33 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是由在此之前执行的代码决定的。

这是反射派上用场的地方。