如何在php中将范围/作用域传递给函数?
类如何在php中将范围/作用域传递给函数?,php,oop,Php,Oop,类A的函数myA调用类B的函数myB,该函数执行导入: class A { function myA() { // ambit variables of myA and class B here like: // $foo = "bar"; // ... $B = new B(); $B->myB(); } } class B { function myB() { // ambit variables of myB a
A
的函数myA
调用类B
的函数myB
,该函数执行导入:
class A
{
function myA()
{
// ambit variables of myA and class B here like:
// $foo = "bar";
// ...
$B = new B();
$B->myB();
}
}
class B
{
function myB()
{
// ambit variables of myB and class B here like:
// $hello = "there";
// ...
return include("file.php");
}
}
我想要的是,在执行导入时,导入脚本将考虑类A
和函数myA
的范围/范围,而不是类B
和函数myB
的范围/范围,然后file.PHP的PHP代码可以知道myA
函数的变量$foo
我怎么做
谢谢 我找到了解决办法。基本上,我使用了函数Closure::bind
静态函数来标记调用者的类范围,extract
函数来标记范围调用者的任何局部变量。以下是如何:
class A
{
function myA()
{
// ambit variables of myA and class B here like:
$foo = "bar";
$myLocalVars = ['foo' => $bar];
$B = new B();
$B->myB($this, $myLocalVars);
}
}
class B
{
function myB($classAmbit, $localVars)
{
$closure = function () use ($localVars)
{
// With extract any local var from caller's ambit is now accesible here
extract($localVars);
return include("file.php");
}
// With Closure::bind, the $this from caller is now accesible in the closure,
// also any of their members, i.e protected, private and public members
$closureBinded = Closure::bind ($closure, $classAmbit, get_class($classAmbit));
return $closureBinded();
}
}
你是说包括在内吗?你为什么不把一个参数传递给myB?是的,我的意思是包含,我不传递参数,因为“myB”的目的是抽象许多档案的包含过程。我最初的问题是为什么?file.php需要或可以访问myA或myB范围的功能是什么?如果没有一个更具体的例子,这将是很难帮助。如果无法使用参数,则控件将在include之后返回myA。file.php是否实现了一个公共接口?一个作用域并不是无缘无故地被称为“作用域”。我能想到的唯一解决方案是在一个可用的类中使用“myB”的参数或turn file.php,这样对您自己来说就简单了