【发布时间】:2015-10-24 01:43:56
【问题描述】:
我一直在实现一个 Wordpress 插件,但在查明变量是否已声明时遇到了问题。
假设我有一个名为Hello 的模型;该模型有 2 个变量,分别为 hello_id 和 hello_name。
在数据库中,我们有一个名为 hello 的表,其中有 3 列分别为 hello_id、hello_name、hello_status。
我想检查一个变量是否已声明,如果有,请设置一个值。
abstract class MasterModel {
protected function setModelData($data)
{
foreach($data as $key=>$value){
if(isset($this->{$key})){ // need to check if such class variable declared
$this->{$key} = $value;
}
}
}
}
class Hello extends MasterModel{
public $hello_id;
public $hello_name;
function __construct($hello_id = null)
{
if ($hello_id != null){
$this->hello_id = $hello_id;
$result = $wpdb->get_row(
"SELECT * FROM hello WHERE hello_id = $hello_id"
, ARRAY_A);
$this->setModelData($data);
}
}
}
我这样做的主要原因是让我的代码在未来可扩展。例如,我可能不会使用数据库中的某些字段,但将来我可能需要它们。
【问题讨论】:
-
isset() 没有工作吗?