Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中将范围/作用域传递给函数?_Php_Oop - Fatal编程技术网

如何在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,这样对您自己来说就简单了