像 PHP 中的“#if defined”这样的预处理

Preprocessing like "#if defined" in PHP

我有以下问题:

我正在使用 PHP 编写 SOAP 服务器应用程序。但我必须以两种不同的方式做到这一点,一种是供外部使用(对所有人),另一种是仅供导入。并且导入应用程序的可能性更大一点,但其他都是一样的。

在 C 中我会写这样的东西(使用预处理器):

#ifdef INTERNAL
int funktion( int ok, double asdfg, const char *aaa){
#else
int funktion( int ok, double asdfg){
#endif
    return 0;
}

我知道PHP中的函数defined(),但它并没有真正做我想做的事情(我认为)。 但是有类似的东西吗?

当然我可以写两个不同的应用程序,但如果有这样的东西就太好了......

感谢您的帮助!

编辑: 我知道通常可以编写条件函数,例如

if(CST){
     function asdf($asdf){
     }
}
else{
    function asdf(){}
}

但我在 Class 中需要它,但它在那里不起作用...

亲切的问候!

在PHP中没有这样的预处理结构,因为PHP没有被编译。但是在PHP中classes是可以有条件定义的。所以你可以分两步完成:

  1. 使用完整选项(第 3 个参数)定义 class,但将那些敏感成员定义为 protected 而不是 public

  2. 有条件地扩展 class,通过新名称和适当的签名提供对 protected 成员的访问。其他 public 成员不必明确提及,因为它们照常继承

这是一个例子:

define('INTERNAL', false);

// Define complete class, but with members set to protected
// when they have constraints depending on INT/EXT access
class _myClass {
    protected function _funktion ($ok, $str, $id = -1) {
        echo  "arguments: $ok,$str,$id";
    }
    public function otherFunc() {
        echo "other func";
    }
}

// Define myClass conditionally
if (INTERNAL) {
    class myClass extends _myClass{
        // give public access to protected inherited method 
        public function funktion ($ok, $str, $id) {
            $this->_funktion ($ok, $str, $id);
        }
    }
} else {
    class myClass extends _myClass{
        // give public access to protected inherited method, but only
        // with 2 parameters
        function funktion ($ok, $str) {
            $this->_funktion ($ok, $str);
        }
    }
}


$obj = new myClass();

// if signature has 2 arguments, third is ignored 
$obj->funktion(1, 'test', 3);
// other methods are availble 
$obj->otherFunc();

我知道这是一个老问题,有点不同,但 FWIW 我正在寻找一种比我现在使用的更优雅的方式来获得 debug/release 运行,即一种条件编译。

到目前为止,我找不到比在 assert (https://www.php.net/manual/en/function.assert.php) 中 运行 一些代码更好的东西了。这是可能的用例之一:

function debugMsg(string $message): bool
{
    echo $message . PHP_EOL;

    return true;
}

.....
assert(debugMsg("some debug message"));

然后我可以有条件地将 'zend.assertions' 设置为 '0' 用于发布或设置为 '1' 用于调试(使用 ini_set)。

因此,进行非常繁重的处理(性能测试)并 运行在“调试模式”下运行代码,给了我大量的输出,让我可以看到很多用于调试的细节,但它的工作速度比“发布模式”慢 10 倍,并且跳过了所有日志记录。

注:

  • 该代码(函数调用)应该 return true 才能正常工作
  • 'zend.assertions'不应该是php.ini中的'-1',否则assert的代码甚至都不会生成执行,因此无法控制在代码里面。