【发布时间】:2020-11-29 11:36:59
【问题描述】:
我很难弄清楚如何实现类似于以下 Python 代码的代码:
class _Mapper(object):
# Holds the name of the function to call when we want to predict a value.
# There may be dozens of these _Mapper objects stored in an array which are
# created by calling _create_couplet() in a nested loop
def __init__(self, estimator):
self.estimator = estimator
def _create_couplet(pairings, A, B):
# Gets the data for the pairing from the pairings class and returns a Mapper
# object containing the function (either function 1 or function2 - defined in
# pairing class) that we'll use to to predict the value
if A < B:
return (_Mapper(pairings.function1))
else:
return (_Mapper(pairings.function2))
# Use the function (either function1 or function2) stored in _Mapper.estimator
# (created by _create_couplet) to estimate the new value based on the old value
newValue = _Mapper.estimator(oldValue)
本质上,它创建了一个 _Mapper 对象数组,每个对象都包含一个对稍后用于计算值的函数(函数 1 或函数 2)的引用。关键步骤似乎是:
newValue = _Mapper.estimator(oldValue)
获取保存在 _Mapper.estimator 中的函数,然后将 oldValue 传递给 newValue = function1(oldValue) 或 newValue = function2(oldValue)
我正在尝试在 PHP 中实现类似的东西,但在 CLI 中运行它时似乎出现了某种无限循环。看来函数名没有存储在
class Pairings {
// Define the two functions (these are just placeholders)
public function function1($value = null) {
return $value * 2;
}
public function function2($value = null) {
return $value * 4;
}
}
class _Mapper {
function __construct($estimator) {
// This should store the function that we are going to
// use based on the value of A & B in _create_couplet()
$this->estimator = $estimator;
}
function estimator($value) {
// This should pass the value specified to either function1()
// or function function2() and should return the result. It
// doesn't !
return $this->estimator($value);
}
}
function _create_couplet($pairing, $A, $B) {
// Based on the value of A or B store the appropriate function
if ($A < $B) {
return (new _Mapper($pairing->function1()));
} else {
return (new _Mapper($pairing->function2()));
}
}
// Set up some values
$oldValue = 10;
$A = 10;
$B = 5;
// Define the pairing
$pairing = new Pairings;
// Create the _Mapper object
$couplet = _create_couplet($pairing, $A, $B);
// Pass oldValue into the appropriate function and get the result back
$newValue = $couplet->estimator($oldValue);
echo ("New value: $newValue");
我确信我犯了一个简单的错误,但我看不出我错过了什么。如何将函数名称存储在对象中,然后将参数传递给它,以便存储的函数使用该参数并返回一个值?
【问题讨论】:
-
$pairing->function1()this 执行方法...$pairing->function1this 指的是方法...在 PHP 中你必须有一个“Callable”...这也可以是一个字符串(用于函数)或数组(用于类方法),如下所示:[$pairing, 'function1']。编辑:您必须使用call_user_func或类似名称来调用它 -
感谢您的回复。 call_user_func 会去哪里?在配对类中?
-
不,在 Mapper 中,当访问 Pairing 时(估计方法)... Mapper 根本不需要知道 Pairing 类,有一个“Callable”就足够了。请参阅下面的评论,@Kern 解释得很好......