Fifi
Fifi

Reputation: 3605

PHP Declare method in class if statement

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

Upvotes: 1

Views: 285

Answers (2)

Mr Robot
Mr Robot

Reputation: 1216

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

Upvotes: 1

Mainul Hasan
Mainul Hasan

Reputation: 699

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();

Upvotes: 0

Related Questions