dsoihsnz85757 2017-05-16 21:15
浏览 54
已采纳

通过一个函数将参数传递给另一个函数

I'm writing a PHP Wordpress plugin where I want to be able to call the functions I've defined in other parts of my website (e.g. on page templates).

I want to be able to pass arguments to my functions like so:

// Contained on Page Template to display content

$args1 = 'Hello';
$args2 = 'Goodbye';

saySomething( $args1, $args2);

// Contained within plugin file

function saySomething ($args1, $args2){

  //echo $args1 //Test Only
  //echo $args2 //Test Only

  function sayHello () {
      echo $args1;
  }

  function sayGoodbye () {
    echo $args2;
  }
}

I've already use 'include_once' to make sure I can call functions in my plugin file. However, for some reason the sub-functions (for want of a better word!) don't seem to work. I've tried a few things, including redefining the arguments within the first function (e.g. $newargs = $args1). Any thoughts greatly appreciated.

  • 写回答

2条回答 默认 最新

  • doufan9290 2017-05-16 21:28
    关注

    A couple of main things.

    1. You've defined the sayHello and sayGoodbye functions, but they are not called.
    2. sayHello and sayGoodbye refer to variables $args1 and $args2, but those variables are undefined within their scope.

    Here's a way to make it work with minimal changes to your code. I changed the names of the variables to emphasize the fact that the variables in sayHello and sayGoodbye are not the same variables as the ones in saySomething.

    function saySomething ($args1, $args2){
    
      function sayHello ($x) {   // update the function signature so that it takes an argument
          echo $x;               // use the given parameter
      }
    
      function sayGoodbye ($y) {
        echo $y;
      }
    
      // call the functions
      sayHello($args1);
      sayGoodbye($args2);
    }
    

    One other thing:

    Contrary to what it looks like, sayHello and sayGoodbye are available in the same scope as saySomething. They are not defined only within the scope of that function, even though they are written there. In effect it's the same thing as writing:

    function saySomething ($args1, $args2){
      sayHello($args1);
      sayGoodbye($args2);
    }
    
    function sayHello ($x) {
      echo $x;
    }
    
    function sayGoodbye ($y) {
      echo $y;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)