使用变量调用PHP类变量

时间:2011-07-12 15:33:39

标签: php

我有一个PHP类定义,它使用一个名为databaseObject的类用于所有典型的数据库方法(Crud,Etc)。我最近更改了我的数据库结构,以便每个表中的id列不再被称为“id”,现在不管表格是什么+ id(例如:Companies Table的id为“companyId”)。所以现在在扩展databaseObject的类中,我包含一个名为$ table_id的静态变量,它保存该表的id名称。我遇到了一个情况,现在我需要调用该类变量。示例代码如下。此代码在PHP 5.3中运行。

//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');

}

2 个答案:

答案 0 :(得分:3)

使用self::$variable而不是static::$variable

答案 1 :(得分:-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由此前执行的代码确定。

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