我不确定术语“通配符”是否可以解释我的观点,但有时在一些现成的脚本中,我们可以调用一个非定义的函数,如find_by_age(23)
,其中age可以是映射到数据库的任何其他函数表记录。所以我可以致电find_by_name
,find_by_email
,find_by_id
等等。那么我们怎么能以程序或面向对象的方式做这样的事情呢?
答案 0 :(得分:5)
您正在寻找的术语是魔法。
基本上是这样的:
class Foo {
public function __call($method,$args) {
echo "You were looking for the method $method.\n";
}
}
$foo = new Foo();
$foo->bar(); // prints "You were looking for the method bar."
对于您正在寻找的内容,您只需过滤掉错误的函数调用并重定向好的函数:
class Model {
public function find_by_field_name($field,$value) { ... }
public function __call($method,$args) {
if (substr($method,0,8) === 'find_by_') {
$fn = array($this,'find_by_field_name');
$arguments = array_merge(array(substr($method,8)),$args);
return call_user_func_array($fn,$arguments);
} else {
throw new Exception("Method not found");
}
}
}
答案 1 :(得分:1)
您可以通过在类中定义__call
魔术方法来使用它们,您只能在类中使用它们。全球范围
引用PHP手册:
<?php
class MethodTest {
public function __call($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}
$obj = new MethodTest;
$obj->runTest('in object context');
MethodTest::runTest('in static context'); // As of PHP 5.3.0
?>
以上示例将输出:
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
答案 2 :(得分:0)
对于程序解决方案,您只需使用字符串连接即可完成工作。您可以通过将其称为strategy pattern的实现来稍微改变一下。
<?php
/**
* Employ a find by name strategy
*/
function find_by_name($name)
{
echo "You are searching for users with the name $name";
return array();
}
/**
* Employ a find by age strategy
*/
function find_by_age($age)
{
echo "You are searching for users who are $age years old";
return array();
}
/**
* Find users by using a particular strategy
*/
function find_using_strategy($strategy='age', $parameter)
{
$results = array();
$search_function = 'find_by_' . $search_field;
if (function_exists($search_function)) {
$results = $search_function($parameter);
}
return $results;
}
$users = find_using_strategy('name', 'Matthew Purdon');
var_dump($users);