开发者

Echo inside __construct()

开发者 https://www.devze.com 2023-03-31 23:22 出处:网络
How to read variable inside __construct()? Here\'s the sample code: class Sample { private $test; public function __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.


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

精彩评论

暂无评论...
验证码 换一张
取 消