Search code examples
phpfunctionclassconditional-statementsdeclare

PHP - Declare function in class based on condition


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!


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.