11

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.

Tony
  • 9,672
  • 3
  • 47
  • 75
Chyngyz Sydykov
  • 430
  • 2
  • 6
  • 18

3 Answers3

16

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.."
}
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44
4

Use isset http://php.net/manual/en/function.isset.php

if(isset($var)){

//do stuff

}
Siguza
  • 21,155
  • 6
  • 52
  • 89
kurt
  • 1,146
  • 1
  • 8
  • 18
3

Talking about a nullable class property, to check if it has been initialized:

class MyClass {
  public ?MyType $my_property;
  public \ReflectionProperty $rp;

  public function __construct()
  {
    $this->rp = new \ReflectionProperty(self::class, 'my_property');
  }

  public function myMethod()
  {
    if (!$this->rp->isInitialized($this)) {
      // Do stuff when my_property has never been initialized
    }
  }
}

This is useful when creating a caching system where the value can be null.

  • 1
    This answer is a bit more "expensive" but it's the correct way to know the difference between a property that exists but has not been assigned *anything* yet. `isset()`, `empty()` etc. don't know the difference between "initialized" and `null`, and whether initialized or not, `property_exists()` will be `true` whether it's initialized or not. – cautionbug Jun 13 '23 at 17:21