Reputation: 470
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.
Upvotes: 13
Views: 29378
Reputation: 517
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.
Upvotes: 6
Reputation: 10058
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.."
}
Upvotes: 19
Reputation: 1156
Use isset http://php.net/manual/en/function.isset.php
if(isset($var)){
//do stuff
}
Upvotes: 5