检查变量是否已在 PHP 中初始化

Chy*_*kov 5 php variable-declaration

我一直在实现 wordpress 插件,但我遇到了一个问题,即发现变量是否已声明。

假设我有一个名为“Hello”的模型。该模型有 2 个变量,分别是“hello_id”和“hello_name”。现在让我们假设在数据库上我们有名为 'hello' 的表,其中 3 列分别为 'hello_id'、'hello_name' 和 'hello_status'。现在我想检查变量是否已声明,如果是,则设置值。

代码

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);
       } 
    }
}
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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我这样做的主要原因是让我的代码在未来可扩展。例如,我可能不会使用数据库中的某些字段,但将来我可能需要它们。

非常感谢

你们中的一员

Dan*_*rom 7

你可以使用几个选项

//this will return true if $someVarName exists and it's not null
if(isset($this->{$someVarName})){
//do your stuff
}
Run Code Online (Sandbox Code Playgroud)

您还可以检查属性是否存在以及是否未将其添加到类中。

即使值为 null,property_exists 也返回 true

if(!property_exists($this,"myVar")){
    $this->{"myVar"} = " data.."
}
Run Code Online (Sandbox Code Playgroud)

  • 在 PHP 7.4 中,如果变量根本没有值,则 property_exists 返回 true。在 7.4 之前,属性的默认值为 null。现在情况不再是这样了。 (3认同)