在 PHP 中,是否可以僅在陳述句為 true 時才在類中宣告方法:
class MyClass {
//...
if (mode === 'production'):
public function myMethod() {
// My cool stuffs here
}
endif;
}
uj5u.com熱心網友回復:
不,你不能,但肯定有一些替代解決方案,比如使用繼承。
uj5u.com熱心網友回復:
您可以通過創建限制你的功能作業
object,并呼叫method您的class通過你的病情。例如,
class MyClass {
public function myMethod() {
// My cool stuffs here
return 'Hello there';
}
}
$myObj = new MyClass();
$mode = 'production';
if ($mode === 'production'):
echo $myObj->myMethod();
endif;
即使您可以使用建構式方法并傳遞
$mode值然后回傳值,只有條件為真。
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316358.html
上一篇:2021華為杯數學建模“空氣質量預報二次建模” 思路
下一篇:ifelse停止條件
