从另一个函数的作用域访问变量? [英] Access variable from scope of another function?

查看:79
本文介绍了从另一个函数的作用域访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php
  function foo($one, $two){
    bar($one);
  }

  function bar($one){
    echo $one;
    //How do I access $two from the parent function scope?
  }
?>

如果我有上面的代码,如何从bar()中访问变量$ two,将其作为变量传递(原因未知).

If I have the code above, how can I access the variable $two from within bar(), without passing it in as a variable (for reasons unknown).

谢谢

迈克

推荐答案

创建一个类-您可以将$ two声明为实例字段,所有实例方法都可以访问该字段:

Make a class - you can declare $two as an instance field which will be accessible to all instance methods:

class Blah {
  private $two;
  public function foo($one, $two){
    this->$two = $two;
    bar($one);
  }

  public function bar($one){
    echo $one;
    // How do I access $two from the parent function scope?
    this->$two;
  }
}

这篇关于从另一个函数的作用域访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆