我有一个PHP类定义,它为所有典型的数据库方法(Crud等)使用一个名为databaseObject的类。我最近更改了数据库结构,使每个表中的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');
}
使用self::$variable
而不是static::$variable
你需要的是反射
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
是由在此之前执行的代码决定的。