1

In PHP, is it possible to declare a method in a class only if a statement is true :

class MyClass {

    //...
    
   
    if (mode === 'production'):
    public function myMethod() {
        // My cool stuffs here        
    }
    endif;
}
2
  • 2
    No it isn't ... Commented Oct 9, 2021 at 5:09
  • 1
    No, but you can certainly solve whatever problem you are trying to solve some other way. For example you could use inheritance, or a factory pattern, or perhaps pass an object into the class that either does or does not have the method defined. Commented Oct 9, 2021 at 5:34

2 Answers 2

1

No you can't, but there are certainly some alternative solutions like using inheritance.

Sign up to request clarification or add additional context in comments.

Comments

0

You can limit your function work by creating object and calling the method of your class through your condition. For example,

class MyClass {
    public function myMethod() {
        // My cool stuffs here
        return 'Hello there';
    }
}

$myObj = new MyClass();
$mode = 'production';
if ($mode === 'production'):
    echo $myObj->myMethod();
endif;

Even you can use the constructor method and pass the $mode value and then return value only condition is true.

class MyClass {
    private $mode;
    function __construct($mode) {
        $this->mode = $mode;
    }
    public function myMethod() {
        // My cool stuffs here
        if($this->mode == 'production'){
            return 'Hello there';
        }
        return '';
    }
}

$myObj = new MyClass('production');
echo $myObj->myMethod();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.