phpvariable-declaration

Check if variable been initialized in PHP


I have been implementing a Wordpress plugin and I faced a problem with finding out if a variable has been declared or not.

Let's say I have a model named Hello; this model has 2 variables as hello_id and hello_name.

In the database we have table named hello with 3 columns as hello_id, hello_name , hello_status.

I would like to check if a variable has been declared and, if it has, set a value.

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);
       } 
    }
}

The main reason why I am doing this is to make my code expandable in the future. For example I might not use some fields from the database but in future I might need them.


Solution

  • you can use several options

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

    you can also check if property exists and if it doesn't add it to the class.

    property_exists returns true even if value is null

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