Testing if property exists
PhpPhp Problem Overview
I read on php docs that isset()
is faster than property_exists()
and we should use a combination of both like
if (isset($this->fld) || property_exists($this, 'fld')) {
But why can't I just use isset then?
if (isset($this->fld)) {
Php Solutions
Solution 1 - Php
Because property_exists
will tell you if its even a defined property of the class/object where as isset doesnt make that distinction. for example:
class A {
protected $hello;
}
class B {
}
using property_exists($this, 'hello')
in class A will return true
, while using it in class B will return false
. isset
will return false
in both instances.
Solution 2 - Php
It depends on how your program is done, but if you read the comments in the manual it will help with explaining idiosyncrasies of a function.
http://php.net/manual/en/function.property-exists.php
The important part is here:
> The documentation leaves out the > important case of new properties you > add to objects at run time. In fact, > property_exists will return true if > you ask it about such properties.