【发布时间】:2016-11-18 15:18:33
【问题描述】:
我必须要类,我想将一个方法从 classA 传递给 classB 构造函数,并将其存储在 classB 实例变量中,以便稍后执行。
class A
{
public function execute()
{
$ClassB = new ElgEmpAnalyticsImporterControllerImporterEmporioOrder(ConMW::getDB(), $this -> lPointFile, [$this, 'getLastPoints'] );
$ClassB -> import();
}
public function getLastPoints(Array $keys)
{
$res = [];
forEach ( json_decode( file_get_contents($this -> lastPointFile) ) as $key => $value ):
if ( in_array($key, $keys) ):
$res[$key] = $value;
else:
$res[$key] = '';
endif;
endforeach;
unset($key);
unset($value);
return $res;
}
}
classB
{
public $getLastPoints = null;
public function __construct(callable $getLastPoints)
{
$this -> getLastPoints = $getLastPoints;
}
public function import()
{
$lastPoints = $this -> getLastPoints(['idOrder', 'orderLastExport']);
}
}
尝试像这样执行它我收到错误“调用未定义的方法 getLastPoints()”
我认为问题在于将函数存储在 classB 的实例变量 $getLastPoints 上。我可以得出结论,因为如果我在构造函数上执行该函数,它就可以工作。这意味着如果我像这样更改 classB 的构造函数
classB
{
public $getLastPoints = null;
public function __construct(callable $getLastPoints)
{
$getLastPoints(['idOrder', 'orderLastExport']);
}
}
它有效。
但我需要的是在导入函数中执行外部函数。
有人可以帮帮我吗?
感谢您的宝贵时间,
编辑澄清:我的问题是为什么我可以像这样在构造函数中执行函数:
$lastPoint(a,b)
但是当我将可调用对象分配给这样的实例变量时:
$this -> lastPoint(a,b)
它不起作用。
我读到 php 对变量和函数使用不同的存储。 PHP 可能将可调用的 $lastPoints 视为变量。那么可调用的 $lastPoints 是否可以作为动态函数添加到我的 classB 实例中?
克里斯托弗罗斯
【问题讨论】:
-
这是真的
ElgEmpAnalyticsImporterControllerImporterEmporioOrder吗? -
只需将getLastPoints()方法的值存储在一个变量中到A类中,然后在创建新的B对象时传递该变量
-
对不起 AbraCadaver ElgEmpAnalyticsImporterControllerImporterEmporioOrder 是 ClassB
-
只是一个非常简短的问题:为什么?
-
Damian Dominella:我需要能够在运行时运行该函数。以上是一个样本。这个函数在实际程序中被多次调用,我的返回值不一样。
标签: php