您可能已经发现,当我看到一些有趣的事情但我不知道该怎么做时,我唯一的目标就是弄清楚如何去做。具有基于数据库记录(或数组)的动态方法的 PHP 类就是这种情况。我花了一些时间弄清楚它是如何完成的。
PHP 数组中的示例 MySQL 记录
$record = array( 'id' => 12, 'title' => 'Greatest Hits', 'description' => 'The greatest hits from the best band in the world!' );
假设我们根据通过 MySQL 查询检索到的记录创建了上述数组。
具有动态函数的 PHP 类
/* create class */ class Record { /* record information will be held in here */ private $info; /* constructor */ function Record($record_array) { $this->info = $record_array; } /* dynamic function server */ function __call($method,$arguments) { $meth = $this->from_camel_case(substr($method,3,strlen($method)-3)); return array_key_exists($meth,$this->info) ? $this->info[$meth] : false; } /* uncamelcaser: via http://www.paulferrett.com/2009/php-camel-case-functions/ */ function from_camel_case($str) { $str[0] = strtolower($str[0]); $func = create_function('$c', 'return "_" . strtolower($c[1]);'); return preg_replace_callback('/([A-Z])/', $func, $str); } }
第一步是创建一个非常原始的类,它有一个接收记录数组的构造函数和一个在类方法被调用时执行的 __call 魔术方法。当调用方法时,我们解析方法名称以删除“get”并检查相应的数组键是否存在。如果键存在,我们返回它的值——如果键不存在,我们简单地返回 false。
PHP 示例用法
/* usage */ $Record = new Record( array( 'id' => 12, 'title' => 'Greatest Hits', 'description' => 'The greatest hits from the best band in the world!' ) ); /* proof it works! */ echo 'The ID is: '.$Record->getId(); // returns 12 echo 'The Title is: '.$Record->getTitle(); // returns "Greatest Hits" echo 'The Description is: '.$Record->getDescription(); //returns "The greatest hits from the best band in the world!"
上面我们将数组传递给类,然后能够通过“get”函数检索值。太棒了!
上面的例子并不是动态函数创建的最动态或最现实的用法,但这个例子会让你先爬再走。如果您有更好的示例或实际用途,请告诉我。