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

时间:2013-09-05 14:42:57

标签: php function class conditional-statements declare

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

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

        }
    }
}

我知道这可能不是最佳做法,但我需要针对我遇到的一个非常具体的问题这样做,所以无论如何都要做到这一点?

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

谢谢!

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

这取决于您的具体用例,而且我没有足够的信息来提供具体的答案,但我可以想到一个可能的解决方法。

使用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并且不添加新方法。

答案 2 :(得分:0)

class Test {
    public function somefunction() {

    }
}

实际上是你所需要的。

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

答案 3 :(得分:0)

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