PHP - 根据条件在类中声明函数


PHP - Declare function in class based on condition

有没有办法做这样的事情:

class Test {
    if(!empty($somevariable)) {
        public function somefunction() {
        }
    }
}

我知道这可能不是最佳实践,但是对于我遇到的一个非常具体的问题,我需要这样做,那么无论如何都可以这样做吗?

我只希望该函数包含在类中,如果该变量(与 URL 参数绑定)不为空。 正如现在所写,我得到错误:语法错误,意外T_VARIABLE,期望T_FUNCTION

谢谢!

这取决于您的特定用例,我没有足够的信息来给出具体的答案,但我可以想到一种可能的解决方法。

使用 if 语句扩展类。将除一个函数之外的所有内容都放在AbstractTest.

<?php
abstract class AbstractTest 
{
    // Rest of your code in here
}
if (!empty($somevariable)) {
    class Test extends AbstractTest {
        public function somefunction() {
        }
    }
} else {
    class Test extends AbstractTest { }
}

现在,类 Test 只有方法somefunction如果$somevariable不为空。否则,它直接扩展AbstractTest并且不会添加新方法。

如果变量不为空,则调用所需的函数。

<?php
    class Test {
        public function myFunct() {
            //Function description
        }
    }
    $oTest = new Test();
    if(!empty($_GET['urlParam'])) {
        oTest->myFunc();
    }
?>
class Test {
    public function somefunction() {
    }
}

是你实际需要的。

请注意,类中的函数称为"方法"。

AFAIK 你不能在类范围内有方法之外的条件(如果它流动)

Class Test {
 if (empty($Var)){
    public function Test_Method (){
    }
  }
}

行不通。为什么不让它一直存在,而只在需要时调用该方法?

例:

Class Test { 
  public function Some_Method(){
    return 23094; // Return something for example purpose
  }
}

然后从你的 PHP :

$Var = ""; // set an empty string
$Class = new Test();
if (empty($Var)){
  echo $Class->Some_Method(); // Will output if $Var is empty 
}

也许您尝试验证 OOP 范围内的字符串,然后以以下示例为例:

 Class New_Test {
     public $Variable; // Set a public variable 
    public function Set(){
      $This->Variable = "This is not empty"; // When calling, $this->variable will not be empty
    }
    public function Fail_Safe(){
      return "something"; // return a string
    }
  }

然后超出范围:

  $Class = new New_Test();
  if (empty($Class->Variable)){
     $Class->Fail_Safe(); 
   } // Call failsafe if the variable in OOP scope is empty