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;
}
CodePudding user response:
No you can't, but there are certainly some alternative solutions like using inheritance.
CodePudding user response:
You can limit your function work by creating
object
and calling themethod
of yourclass
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();