我能知道它是如何被称为PHP函数的吗?


Can I know how is called a PHP function?

我正在编写一个函数,它可以返回整数值或将此整数写入文件。我希望这个选择只通过调用函数来完成。我可以吗?

函数如下:

function directory_space_used($directory) {
// Space used by the $directory
  ...
  if ( "call #1" ) return $space_used;
  if ( "call #2" ) {
    $file=fopen(path/to/file, 'w');
    fwrite($file, $space_used);
    fclose($file);
  }
  return null;
}

Call #1:

$hyper_space = directory_space_used('awesome/directory');
echo "$hyper_space bytes used.";

呼叫#2:

directory_space_used('awesome/directory'); // Write in file path/to/file

如果不可能,我可以在函数中使用第二个参数,但我想保持参数的数量尽可能低。

谢谢。

您可以在会话变量中保留计数,但我建议使用第二个参数。这样维护起来更简洁,而且您总是可以设置一个默认值,以便它只用于以下情况之一:

function directory_space_used($directory, $tofile = false) {
// Space used by the $directory
...
if ( $tofile )  {
   $file=fopen(path/to/file, 'w');
   fwrite($file, $space_used);
   fclose($file);
}else{
   return $space_used;
}
  return null;
}

然后命名为

directory_space_used('....', true) // saves in a file
directory_space_used('....') // return int

是的,你可以使用这个神奇的常量

__FUNCTION__

,你可以读一下

在你的函数上再加一个参数,这个参数将是请求来自的函数的名称,之后你可以在if语句中使用它。

这是伪代码:

       //function that you want to compare
        function test1() {
        //do stuff here
        $session['function_name'] = __FUNCTTION__;
        directory_space_used($directory,$function_name);
        }
        //Other function that you want to compare
        function test2() {
        //do stuff here
        $session['function_name'] = __FUNCTTION__;
    }
function directory_space_used($directory) {
        // Space used by the $directory
          ...
           if(isset($session['function_name'])) {
          if ('test1' == $function_name ) return $space_used;
          if ( 'test2' == $function_name ) {
            $file=fopen(path/to/file, 'w');
            fwrite($file, $space_used);
            fclose($file);
          }
        } else {
//something else 
}
          return null;
        }
我认为使用开关柜是更好的选择。这只是一张便条。

test1和test2可以在你的PHP文件和文件夹的任何地方

谢谢大家,似乎更好的方法是在函数中添加第二个参数。没有我想的那么有趣,但它很容易工作,不需要使用大量的代码。