检查变量是否已在 PHP 中初始化
Check if variable been initialized in PHP
我一直在实现一个 Wordpress 插件,但我遇到了一个问题,无法确定变量是否已声明。
假设我有一个名为 Hello
的模型;该模型有 2 个变量 hello_id
和 hello_name
。
在数据库中我们有 table 命名为 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 http://php.net/manual/en/function.isset.php
if(isset($var)){
//do stuff
}
您可以使用多个选项
//this will return true if $someVarName exists and it's not null
if(isset($this->{$someVarName})){
//do your stuff
}
您还可以检查 property exists 是否未将其添加到 class。
property_exists returns 即使值为空也是如此
if(!property_exists($this,"myVar")){
$this->{"myVar"} = " data.."
}
我一直在实现一个 Wordpress 插件,但我遇到了一个问题,无法确定变量是否已声明。
假设我有一个名为 Hello
的模型;该模型有 2 个变量 hello_id
和 hello_name
。
在数据库中我们有 table 命名为 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 http://php.net/manual/en/function.isset.php
if(isset($var)){
//do stuff
}
您可以使用多个选项
//this will return true if $someVarName exists and it's not null
if(isset($this->{$someVarName})){
//do your stuff
}
您还可以检查 property exists 是否未将其添加到 class。
property_exists returns 即使值为空也是如此
if(!property_exists($this,"myVar")){
$this->{"myVar"} = " data.."
}