0 レビュー
2 回答
php-クラス内で使用するためにクラスコンストラクターの外部に変数を割り当てますか?
クラスコンストラクターを使い始めたばかりです。以下のスクリプトでは、クラスの外部から$arg2値を渡します。
変数$someVariable= nを定義して、以下のファイルを含む親ファイルのクラスコンストラクターの外部から設定できるようにするにはどうすればよいですか?
class myClassTest
{
public $var1;
public $var2;
public $var3;
function __construct($arg1,$arg2=$someVariable){ //MAKE $arg2 dynamically set from outside the class
$this->var1 = $arg1;
$this->var2 = $arg2;
$this->var3 = array();
}
わからない
0
レビュー
答え :
解決策:
このように使用するだけですが、お勧めしません
$someGlobalVar = "test";
class myClassTest
{
public $var1;
public $var2;
public $var3;
function __construct($arg1,$arg2=null){
if ($arg2 === null){
global $someGlobalVar;
$arg2 = $someGlobalVar;
}
echo $arg2;
$this->var1 = $arg1;
$this->var2 = $arg2;
$this->var3 = array();
}
}
$class = new myClassTest('something'); //outputs test
わからない
0
レビュー
答え :
解決策:
「外部」変数を使用して引数$arg2のデフォルト値を設定することはできません。 デフォルト値は(論理的に)関数の「定義時間」に設定されます。したがって、これらのパラメータはリテラル(定数)値である必要があります。
したがって、これらはすばらしい宣言です:
function makecoffee($type = "cappuccino") { }
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { }
外部のものを「注入」する場合は、次のようにする必要があります。
$someglobalVariable = 'whatever';
class myClassTest
{
public $var1;
public $var2;
public $var3;
function __construct($arg1,$arg2=null){ //MAKE $numres dynamic from outside the class
global $someglobalVariable;
if ( ! isset( $arg2 ) ) {
$this->var2 = $someglobalVariable;
} else {
$this->var2 = $arg2;
}
$this->var1 = $arg1;
$this->var3 = array();
}
} // end of class
PHPでグローバル変数にアクセスするのは悪いスタイルであることに注意してください(他のオブジェクト指向言語と同様)。
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。