Trong trường hợp bất cứ ai khác muốn tìm một tài sản sâu o không biết chiều sâu, tôi đã đưa ra dưới đây mà không cần phải lặp qua tất cả các thuộc tính được biết đến của tất cả trẻ em. Ví dụ: để tìm $ Foo-> Bar-> baz hoặc $ Foo-> baz, hoặc $ Foo-> Bar-> Baz-> dave, trong đó $ path là một chuỗi như 'foo/bar/baz '.
public function callModule($pathString, $delimiter = '/'){
//split the string into an array
$pathArray = explode($delimiter, $pathString);
//get the first and last of the array
$module = array_shift($pathArray);
$property = array_pop($pathArray);
//if the array is now empty, we can access simply without a loop
if(count($pathArray) == 0){
return $this->{$module}->{$property};
}
//we need to go deeper
//$tmp = $this->Foo
$tmp = $this->{$module};
foreach($pathArray as $deeper){
//re-assign $tmp to be the next level of the object
// $tmp = $Foo->Bar --- then $tmp = $Bar->baz
$tmp = $tmp->{$deeper};
}
//now we are at the level we need to be and can access the property
return $tmp->{$property};
}
Và sau đó gọi với một cái gì đó như:
$propertyString = getXMLAttribute('string'); // '@Foo/Bar/baz'
$propertyString = substr($propertyString, 1);
$moduleCaller = new ModuleCaller();
echo $moduleCaller->callModule($propertyString);
Nguồn
2017-01-15 13:41:06
Cảm ơn một bó! –
Nội dung thú vị +1 và cảm ơn! –
Bất kỳ lợi ích nào của việc sử dụng tùy chọn thứ hai trong lần đầu tiên? – Clox