我一直在想一種方法來動態地使用__call來返回一個類的屬性值,而不是創建一個函數,其唯一目的是返回這些值。我的想法是能夠請求(例如)$ this-> fetch_PersonFirstName(),並且如果設置了$ this-> person [「first_name」]並返回該值,那麼請檢查類。另一個例子是呼叫$ this-> fetch_BookGenreTitle()並且該類返回值$ this-> book [「genre」] [「title」]。我知道這樣的事情需要做一些檢查,以便它自動確定,例如,因爲$ this-> book [「genre_title」]不存在,那麼它應該檢查$ this-> book [「流派」] [「標題」]。如何使用__call來動態返回屬性值
到目前爲止,我已經想出了代碼(出於某種原因)用於返回數組的值(例如我的人例子),但是當我嘗試返回多維數組的值時,我的問題很快發展(比如用我上面的書中的例子)。在腦海中,我仍然試圖想方法來檢查__call方法的存在,如果它不存在,那麼另一個。
請在這裏拋出一條線。我一直在撞牆,試圖弄明白這一點,這讓我很難過。
<?php
class Test
{
protected $person;
protected $book;
public function __construct()
{
$this->person["first_name"] = "John Smith";
$this->book["genre"]["title"] = "Suspense";
}
public function __call($method, $args)
{
$args = implode(", ", $args);
if (preg_match("/^fetch_([A-Z]{1,}[a-z]{1,})(.*)?/", $method, $match))
{
print_r($match);
echo "<br><br>";
$property = strtolower($match[1]);
$indexes = $match[2];
if (property_exists("Test", $property))
{
if ($indexes)
{
$indexes = preg_split("/(?<=[a-z])(?=[A-Z])/", $indexes);
$num_indexes = count($indexes);
$count_indexes = 1;
for ($count=0; $count<$num_indexes; $count++)
{
$record = strtolower($indexes[$count]);
$index .= $record;
$array .= "{$record}";
$var_index = $index;
$var_array = $array;
echo $var_index." {$count}<br>";
echo $var_array." {$count}<br>";
//print_r($this->{$property}{$var_array});
if ($count_indexes == $num_indexes)
{
if (isset($this->{$property}{$var_index}))
{
return $this->{$property}{$var_index};
}
else
{
return $this->{$property}{$var_array};
}
}
else
{
$index .= "_";
}
$count_indexes++;
}
echo "<br><br>";
}
else
{
return $this->{$property};
}
}
}
}
}
?>
<?php
$test = new Test();
echo $test->fetch_PersonFirstName();
echo "<br><br>";
echo $test->fetch_BookGenreTitle();
?>
不要懶惰。添加你需要的吸氣劑,而不是引發__呼吸的性能損失,更不用說做了這麼多工作的人。 – Gordon 2010-10-28 13:18:50