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;
}
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;
}
You can limit your function work by creating
objectand calling themethodof yourclassthrough 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
$modevalue 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();