使用变量调用PHP类变量
我有一个PHP类定义,它对所有典型的数据库方法(Crud等)使用一个名为databaseObject的类。我最近更改了数据库结构,使每个表中的id列不再称为“id”,而是表中包含的任何id+id(例如:companys表的id为“companyId”)。因此,现在在扩展databaseObject的类中,我包含了一个名为$table_id的静态变量,该变量保存该表的id名称。我遇到了一种情况,现在我需要调用该类变量。下面是示例代码。这段代码是在PHP5.3中运行的使用变量调用PHP类变量,php,Php,我有一个PHP类定义,它对所有典型的数据库方法(Crud等)使用一个名为databaseObject的类。我最近更改了数据库结构,使每个表中的id列不再称为“id”,而是表中包含的任何id+id(例如:companys表的id为“companyId”)。因此,现在在扩展databaseObject的类中,我包含了一个名为$table_id的静态变量,该变量保存该表的id名称。我遇到了一种情况,现在我需要调用该类变量。下面是示例代码。这段代码是在PHP5.3中运行的 //databaseObjec
//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
而不是静态::$variable
您需要的是
通过Contract::$table_id
访问字段名,并获取值contracd
。因此,如果我理解正确,您希望获得$contract->contract
,但名称contract
是由在此之前执行的代码决定的
这就是反射派上用场的地方。我认为这不是问题所在。他已经有了静态成员,所以我想他已经知道如何与他们合作了。我敢打赌,现在他在问如何访问class字段,该字段暴露了$table_id中的名称。这是有道理的。为什么?请阅读这里的文档:并回答,为什么在这种情况下static::不正确?
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"