1

How to read variable inside __construct()?

Here's the sample code:

class Sample {
   private $test;

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

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

What is wrong with this code? Because __construct is automatic, I just thought that it will run on class sample and read it automatically.

Is it possible to echo this out without touching __construct()? Thank you.

Ryan
  • 1,783
  • 8
  • 27
  • 42

1 Answers1

7

You need to make $test public. When it's private, it is only readable from within the class.

class Sample {
   public $test;

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

$sample = new Sample();
echo $sample->test;
brianreavis
  • 11,562
  • 3
  • 43
  • 50