PHP 在 class if 语句中声明方法
PHP Declare method in class if statement
在 PHP 中,是否可以仅在语句为真时在 class 中声明方法:
class MyClass {
//...
if (mode === 'production'):
public function myMethod() {
// My cool stuffs here
}
endif;
}
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();
不可以,但肯定有一些替代解决方案,例如使用继承。
在 PHP 中,是否可以仅在语句为真时在 class 中声明方法:
class MyClass {
//...
if (mode === 'production'):
public function myMethod() {
// My cool stuffs here
}
endif;
}
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();
不可以,但肯定有一些替代解决方案,例如使用继承。