我一直在想一种方法来动态地使用__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