1

__construct()内の変数を読み取る方法は?

サンプルコードは次のとおりです。

class Sample {
   private $test;

   public function __construct(){
      $this->test = "Some text here.";
   }
}

$sample = new Sample();
echo $sample->test;

このコードの何が問題になっていますか?__constructは自動であるため、クラスサンプルで実行され、自動的に読み取られると思いました。

__construct()に触れずにこれをエコーアウトすることは可能ですか?ありがとうございました。

4

1 に答える 1

7

$test 公開する必要があります。プライベートの場合、クラス内からのみ読み取ることができます。

class Sample {
   public $test;

   public function __construct(){
      $this->test = "Some text here.";
   }
}

$sample = new Sample();
echo $sample->test;
于 2011-09-01T01:15:52.640 に答える