回调__construct()

Rya*_*yan 1 php echo construct

如何在__construct()中读取变量?

这是示例代码:

class Sample {
   private $test;

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

$sample = new Sample();
echo $sample->test;
Run Code Online (Sandbox Code Playgroud)

这段代码有什么问题?因为__construct是自动的,我只是认为它将在类示例上运行并自动读取它.

是否有可能在不触及__construct()的情况下回应这个问题?谢谢.

bri*_*vis 7

你需要$test 公开.当它是私有的时,它只能从类中读取.

class Sample {
   public $test;

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

$sample = new Sample();
echo $sample->test;
Run Code Online (Sandbox Code Playgroud)