Hubro
Hubro

Reputation: 59383

Check if a class has a field by string

I would Google this, but honestly I have no idea what to search for

Say I have this class

class a
{
    public $a_a, $a_b, $a_c;
}

$true = "a_a";
$false = "a_e";

How do I use the strings to prove that the class contains the field a_a, but not a_e ?

Thanks

Upvotes: 3

Views: 1535

Answers (2)

Gordon
Gordon

Reputation: 317119

With

In your case:

var_dump( property_exists('a', 'a_a') ); // TRUE

You could also use the Reflection API, but that's overkill for this UseCase:

$reflector = new ReflectionClass('a');
var_dump( $reflector->hasProperty('a_e') ); // FALSE

Upvotes: 7

NikiC
NikiC

Reputation: 101936

You could use property_exists or Reflection. But you should know that before PHP 5.3 property_exists checked the visibility of the property, too. So, if you are using PHP 5.2 and want to check the existence of a private property you must use Reflection.

Upvotes: 1

Related Questions