0

わかりました、少し問題があります。シナリオは次のとおりです。test2 のコンストラクターを取得して、main_class のコンストラクターによって設定された main_class 内にあるクラス プロパティ test にアクセスできるようにする必要があります。それを機能させる方法がわかりません。システムがまさにこのように機能する必要があります。さて、クラス定義でこのようにコードでクラス変数を設定すると、これは機能var test = "hello";しますが、もちろんこの場合、main_class::test はコンストラクターによって設定され、「var」ではないため、機能しません。動作しません。

これが私のコードの非常に単純化されたバージョンです:

index.php:

<?php

class main_class
{
    private $test2;
    public function __construct()
    {
        $this->test2 = array();
        include("./test1.php");
        $var_name = "test";
        $this->$var_name = new test1();
    }

    protected function do_include()
    {
        include("./test2.php");
        $this->test2["test2"] = new test2();
    }
}

$test = new main_class();

?>

test1.php:

class test1 extends main_class
{
    public function __construct()
    {
        $this->do_include();
    }
}

?>

test2.php:

class test2 extends test1
{
    public function __construct()
    {
        print_r($this->test);
    }
}

?>

このコードでは、次のエラーが発生します: Notice: Undefined property: test2::$test

前もって感謝します...

4

1 に答える 1

1

問題の一部は、test2 クラスで親コンストラクターを呼び出していないことにあると思われます。

class test2 extends test1
{
    public function __construct()
    {
        parent::__construct();
        print_r($this->test);
    }
}

その行が省略されている場合、test2 コンストラクターは test1 コンストラクターを完全にオーバーライドし、$this->do_include()呼び出されることはありません。

また、 を呼び出すとき$this->test2["test2"] = new test2();は、現在のインスタンスに関連付けられていない、このクラスの新しいインスタンスを作成していることに注意してください。

明確にするために、イベントの順序は次のとおりです。

$test = new main_class(); // calls the constructor of main_class:

public function __construct()
{
    $this->test2 = array();
    include("./test1.php");
    $var_name = "test";
    $this->$var_name = new test1();
}

それで:

$this->$var_name = new test1(); // calls the constructor of test1:

public function __construct()
{
    $this->do_include();
}

... main_class から do_include() を呼び出します:

protected function do_include()
{
    include("./test2.php");
    $this->test2["test2"] = new test2();
}

それで:

$this->test2["test2"] = new test2(); // calls the constructor of test2:

public function __construct()
{
    print_r($this->test);
}

これにより新しいオブジェクトが作成され、そのコンストラクターで行っていることは、まだ存在しない変数 ($test) を出力することだけです...作成するために何もしていないためです。

于 2013-09-30T17:56:25.390 に答える