I have been implementing wordpress plugin and I faced a problem with finding out was variable been declared or not.
let's say i have a model named 'Hello'. this model has 2 variables as 'hello_id' and 'hello_name'. Now let's assume that on database we have table named 'hello' with 3 columns as 'hello_id', 'hello_name' , 'hello_status'. Now I would like to check if variable has been declared and if yes then set value.
code
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;
}
}
}
}
The main reason why I am doing this is to make my code expandable in future. for example i might not use some fields form database, but in future i might need them.
Thank you very much
One of you
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.."
}