PHP-基于条件在类中声明函数

PHP-基于条件在类中声明函数,php,function,class,conditional-statements,declare,Php,Function,Class,Conditional Statements,Declare,有没有办法做到这一点: class Test { if(!empty($somevariable)) { public function somefunction() { } } } 我知道这可能不是最好的做法,但我需要为我遇到的一个非常具体的问题这样做,所以无论如何都要这样做吗 如果变量(绑定到URL参数)不是空的,我只希望该函数包含在类中。正如现在所写的,我得到了错误:语法错误,意外的T_变量,预期的T_函数 谢谢 如果变量不为空,则调用所

有没有办法做到这一点:

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

        }
    }
}
我知道这可能不是最好的做法,但我需要为我遇到的一个非常具体的问题这样做,所以无论如何都要这样做吗

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


谢谢

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

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

这就是你真正需要的


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

a好的,类范围内的方法外不能有条件(如果有条件)

这是行不通的。为什么不让它一直存在,而只在需要时调用方法呢

例如:

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

这取决于您的具体用例,我没有足够的信息给出具体的答案,但我可以想出一个可能的解决方案

使用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 { }
}

我需要针对我遇到的一个非常具体的问题执行此操作
-欢迎您在此处表达您非常具体的问题,并获得适当的解决方案。这比试着在移动你发明的方轮时得到帮助要好得多。让您知道,大多数“非常具体的问题”都是简单而琐碎的情况,都有常见的解决方案。当所需变量不为空时调用该函数。或者在函数中添加IF条件,当所需变量不为空时,函数代码将运行。我将尝试发布特定问题,这可能是一个更好的主意。我尝试了这个方法,但我只在类中是否存在此方法时得到了所需的结果,因此它不起作用。感谢lingo课程(不是挖苦人,我真的需要忍受它),但是该解决方案对我不起作用,因为我需要函数存在或不存在才能得到我想要的结果。@user2278120-函数存在与否应该没有什么区别。函数只有在某个地方被调用时才应该有效果。否则,它就是一块没有任何作用的代码。@user2278120是否考虑过以这里的方法为例,然后从PHP
if(empty($var)){$Class->method();}
将其移出类范围?因此,您只在需要时调用它。这很有效,但我最终解决了核心问题。感谢大家的帮助。
  $Class = new New_Test();
  if (empty($Class->Variable)){
     $Class->Fail_Safe(); 
   } // Call failsafe if the variable in OOP scope is empty
<?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 { }
}