2015-06-20 212 views
-2

除了做下面的代碼之外,有沒有更好的方法來檢查對象是否有幾個給定的屬性?檢查對象是否具有屬性

<?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'); 
?> 
+0

請使用getter和setter - 比'public $ a = 1'更好的模式。 –

+1

更好的方法,或許就像(例如)使用魔法[__isset()方法](http://php.net/manual/ EN/language.oop5.overloading.php#object.isset)? –

+0

你可以使用這個'property_exists($ class,$ property)'來檢查一個屬性是否存在於一個類中。它需要PHP> = 5.3。 – rashidkhan

回答

1

可以使用至少三種方式來做到這一點:

所有這些都表現出如下:

<?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)); 
} 

輸出:

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 

每一列是從我的柱的頂部施加相應的技術的結果。

+0

謝謝rr。認爲可能會有像'array_diff_assoc()'這樣做會... – user1032531

相關問題