我可以在脚本中将PHP函数设为“私有”吗?

时间:2019-12-20 06:45:26

标签: php

我希望某些功能在required时不可见,但在它们所属的脚本中可见。
例如:

required.php:

<?php
function privateFunction() {
    echo 'from private function\n';
}
echo 'from required.php: ';
privateFunction();

index.php:

<?php
require './required.php';
echo 'from index.php: ';
privateFunction(); // I want this to give an error like "private function called outside the script it has been declared".

我已经尝试制作函数private,但是它仅给出解析错误。

3 个答案:

答案 0 :(得分:0)

required.php:

<?php
class A {
    private function privateFunction() {
        echo 'from private function\n';
    }
}

答案 1 :(得分:0)

一般来说,这可能是个坏主意(请参阅上面的注释),但是以下内容可以满足您的要求。

它使用debug_backtrace()来获取函数的文件名,然后获取函数的调用者的文件名,并进行比较。如果它们不匹配,则会引发异常:

function assertCalledByCurrentScript(): void
{
  $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  if (isset($backtrace[1]) && $backtrace[0]['file'] !== $backtrace[1]['file']) {
    throw new \BadFunctionCallException("Cannot call {$backtrace[1]['function']} from outside of its defining script.");
  }
}

然后像这样使用它:

function privateFunction()
{
  assertCalledByCurrentScript();

  // rest of your "private" function here
}

答案 2 :(得分:0)

基本上,您唯一的选择是将私人物品隐藏在类中:

//Your file
class MyClass
{
  public static function myAction()
  {
    $internalStuff = self::internalStuff();
    return 'Using this function you can get what is inside internalStuff: ' . $internalStuff;
  }

  private static function internalStuff()
  {
     return 'Some internal stuff not accessible from outside';
  }
}

function myAction()
{
    return MyClass::myAction();
}

//Otherfile
//require yourfile.php

//You can only use `myAction` as function
echo myAction();

//Or call
echo MyClass::myAction();

//But you cannot use `internalStuff
echo MyClass::internalStuff();