【问题标题】:Check if variable been initialized in PHP检查变量是否已在 PHP 中初始化
【发布时间】: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() 没有工作吗?

标签: php variable-declaration


【解决方案1】:

您可以使用多个选项

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

你也可以检查property exists是否没有添加到类中。

property_exists 返回 true,即使 value 为 null

if(!property_exists($this,"myVar")){
    $this->{"myVar"} = " data.."
}

【讨论】:

  • 谢谢,property_exists($key,$value) 效果很好。
  • 在 PHP 7.4 上,如果变量根本没有值,property_exists 返回 true。在 7.4 之前,属性的默认值为 null。情况不再如此。
【解决方案2】:

使用 isset http://php.net/manual/en/function.isset.php

if(isset($var)){

//do stuff

}

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 2016-10-03
    • 2022-12-03
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多