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.
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;
精彩评论