Question

Is there a way to do something like this:

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

        }
    }
}

I know this might not be best practice, but I need to do this for a very specific problem I have, so is there anyway to do it?

I just want that function to be included in the class if that variable (which is tied to a URL param) is not empty. As it is written now, I get Error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION

Thanks!

Was it helpful?

Solution

It depends on the your specific use case, and I don't have enough info to give a specific answer, but I can think of one possible fix.

Extend the class, using an if statement. Put everything except the one function in 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 { }
}

Now, the class Test only has the method somefunction if $somevariable isn't empty. Otherwise it directly extends AbstractTest and doesn't add the new method.

OTHER TIPS

Call the required function if the variable is not empty.

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

    }
}

is all you need actually.

Please note that a function inside a class is called 'method'.

AFAIK you cannot have a condition out of the method in class scope (if that flows)

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

    }
  }

}

Will not work. Why not have it constantly exisisting but only call the method when it's needed?

Example:

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

}

Then from your PHP:

$Var = ""; // set an empty string
$Class = new Test();

if (empty($Var)){
  echo $Class->Some_Method(); // Will output if $Var is empty 

}

Perhaps you trying to validate a string within OOP scope, then take this example:

 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
    }
  }

Then out of Scope:

  $Class = new New_Test();
  if (empty($Class->Variable)){
     $Class->Fail_Safe(); 
   } // Call failsafe if the variable in OOP scope is empty
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top