If I declare class variables but don’t assign values, can I check whether those variables have been defined?
eg
class myclass
{
public $myVar;
function myFunction()
{
var_dump(isset($this->myVar));
}
}
Or something like that. It seems that the variable doesn’t exist unless I assign a value ie
class myclass
{
public $myVar = "nothing";
function myFunction()
{
var_dump(isset($this->myVar));
}
}
Any ideas?
isset returns 1 if the variable is defined and is not null.
isset determines if a variable is set and is not NULL. Where my class variable is declared but not assigned a value it appears to be null, hence, isset is still false, so that’s not giving me the value I want.
rpkamp
February 14, 2011, 8:04pm
4
Sound to me you’re looking for [fphp]property_exists[/fphp]
Bang on! Thanks a lot, that did the trick!
OK Here’s another one: How do check the visibility of the variables?
I’ve searched for this, I promise but come up with nothing!
rpkamp
February 15, 2011, 10:52am
7
I don’t think there are methods for that, but there’s always reflection
Some scary stuff going on in there …
Here there be dragons! Yeah, I think I’ll give that one a miss and stick with propert_exists. Cheers!
Generally you might want to put that property_exists as a method of the class, so you could use something like:
if($SomeObject->myVarIsSet()){
Though generally things are given a default value in the constructor - what I’d recommend there is setting it to false by default:
if($SomeObject->myVar !== false){