user1032531
user1032531

Reputation: 26341

Check if object has given properties

Other than doing something like the below code, is there a better way to check if an object has several given properties?

<?php
class myClass
{
    public $a=1;
    public $b=2;
    public $c=3;

    public function checkProperties($obj,$props)
    {
        $status=true;
        foreach($props as $prop) {
            if(!isset($obj->$prop)){$status=false;break;}
        }
        return $status;
    }
}
$myObj=new myClass();
print_r($myObj);
echo($myObj->checkProperties($myObj,array('a','b','c'))?'true':'false');
echo($myObj->checkProperties($myObj,array('a','d','c'))?'true':'false');
?>

Upvotes: 0

Views: 6518

Answers (1)

rr-
rr-

Reputation: 14851

You can use at least three ways to do it:

All of these are demonstrated below:

<?php
class myClass
{
    public $a=1;
    public $b=2;
    public $c=3;
}

$myObj = new myClass();
$reflectionClass = new ReflectionClass($myObj);
foreach (['a', 'b', 'c', 'd'] as $property)
{
    printf("Checking if %s exists: %d %d %d\n",
        $property,
        property_exists($myObj, $property),
        isset($myObj->$property),
        $reflectionClass->hasProperty($property));
}

Output:

Checking if a exists: 1 1 1
Checking if b exists: 1 1 1
Checking if c exists: 1 1 1
Checking if d exists: 0 0 0

Each column is a result of applying corresponding technique from the top of my post.

Upvotes: 7

Related Questions