Search code examples
phpechoconstruct

Echo inside __construct()


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.


Solution

  • 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;