【发布时间】:2019-12-20 06:45:26
【问题描述】:
我希望某些函数在 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,但它只会给出解析错误。
【问题讨论】:
-
为什么不使用 OOP?
-
使用类并将函数设为私有。
-
@DevsiOdedra 我知道,但如果我这样做,将无法从“required.php”脚本访问该函数,并且我无法将类标记为“私有”,可以吗?
-
您不能将普通函数设为私有。函数在设计上是全局的。您可以制作类似:
$func = function () { ... }。然后您可以将其用作$func();。这样,您至少可以将其限制在写入的范围内,并且在完成后可以取消设置。 -
如果您向我们解释为什么您需要这个以及它的用途,我们会更容易想出一个好的解决方案。现在,听起来有点像XY problem
标签: php