【问题标题】:Preprocessing like "#if defined" in PHP预处理,如 PHP 中的“#if defined”
【发布时间】:2016-08-19 08:27:34
【问题描述】:

我有以下问题:

我正在使用 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(){}
}

但我需要它在一个类中,它在那里不起作用......

亲切的问候!

【问题讨论】:

  • PHP 不是编译语言。没有这样的编译器指令。但是你能解释一下你的需求吗?真的要决定是否有第三个参数吗?如果是这样,那可以通过不同的方式解决。
  • 嗯,我知道php没有编译。但我希望有一些解决方法......它需要这样的东西:对于普通用户,例如function add() 有 3 个参数,但对于导入,我也需要数据库 ID。在函数中我需要构建 SQL 语句。通常,ID 是 auto_incremented,但如果给出...“如果是这样,那可以用不同的方式解决”带有可选参数(如 function add($test,$test2,$asdf=NULL)?我知道,但这不是我需要的,因为普通用户必须不要使用第三个参数...但是感谢您的帮助!
  • 不,我没有考虑可选参数。您可以有条件地定义一个函数,因此根据该条件在两个不同的签名中。
  • Ähm,但我认为不在课堂内......但非常感谢!
  • 如果您正在寻找具有类方法的解决方案,您能否在问题中指定该要求?

标签: php web compilation conditional preprocessor


【解决方案1】:

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

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

  2. 有条件地扩展类,通过新名称和适当的签名提供对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();

【讨论】:

  • 是的。我的意思是,这并不是我真正想看到的解决方案,但它似乎是唯一可能的......谢谢大家!
猜你喜欢
  • 2014-11-19
  • 2018-06-18
  • 2018-12-29
  • 1970-01-01
  • 2017-04-19
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
相关资源
最近更新 更多